Choosing a Combobox value without triggering the SelectionChanged event

I have a ComboBox:

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

And I installed the list items in the code behind the 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 SelectedIndex, the event SelectionChangedfires.

How can I install ItemSourceand install SelectedIndexwithout triggering an event SelectionChanged?

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

+3
source share
2 answers

You can solve this problem with data binding:

private int _sourceIndex;
public int SourceIndex
{
    get { return _sourceIndex; }
    set
    {
        _sourceIndex= value;
        NotifyPropertyChanged("SourceIndex");
    }
}

private List<ComboBoxItem> _sourceList;
public List<ComboBoxItem> SourceList
{
    get { return _sourceList; }
    set
    {
        _sourceList= value;
        NotifyPropertyChanged("SourceList");
    }
}

public ClientReports()
{
    InitializeComponent();

    // Set the DataContext
    DataContext = this;

    // set the sourceIndex to 0
    SourceIndex = 0;

    // SourceList initialization
    source = ... // get your comboboxitem list
    source.Insert(0, new ComboBoxItem { Content = " - select - "});
    SourceList = source
}

In XAML bind SelectedItem and ItemsSource

<ComboBox Name="drpRoute" 
   ItemsSource="{Binding SourceList}"
   SelectedIndex="{Binding SourceIndex}" />

, SourceIndex , , , , MVVM, WPF.

+4

SelectionChanged , . , , , @Viv, , , . , , - , , .

: :

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
}
+7

All Articles