Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Combobox 's selected value without firing SelectionChanged event

Tags:

c#

wpf

I have a ComboBox:

<ComboBox Name="drpRoute" SelectionChanged="drpRoute_SelectionChanged" />

And I set the list items in the code behind file:

public ClientReports()
{
    InitializeComponent();
    drpRoute.AddSelect(...listofcomboxitemshere....)
}


public static class ControlHelpers
{
    public static ComboBox AddSelect(this ComboBox comboBox, IList<ComboBoxItem> source)
    {
        source.Insert(0, new ComboBoxItem { Content = " - select - "});

        comboBox.ItemsSource = source;
        comboBox.SelectedIndex = 0;

        return comboBox;
    }
}

For some reason, when I set the SelectedIndex, the SelectionChanged event get's fired.

How on earth do I set the ItemSource and set the SelectedIndex without firing the SelectionChanged event?

I am new to WPF, but surely it should not be as complicated as it seems? or am I missing something here?

like image 601
stoic Avatar asked Dec 09 '22 09:12

stoic


1 Answers

The SelectionChangedevent will fire regardless if it was set through code or by user interaction. To get around this you will need to either remove the handler when you are changing it in code as @Viv suggested or add a flag to ignore the changes while you are changing it in code. The first option will not fire the event since you are not listening to it and in the second, you will need to check the flag to see if it was triggered by a change in code.

Update: Here's an example of using a flag:

bool codeTriggered = false;

// Where ever you set your selectedindex to 0
codeTriggered = true;
comboBox.SelectedIndex = 0;
codeTriggered = false;

// In your SelectionChanged event handler
if (!codeTriggered)
{
   // Do stuff when user initiated the selection changed
}
like image 85
evanb Avatar answered Dec 11 '22 09:12

evanb