How to disable SelectionChanged when changing ItemsSource

I have a ComboBox with ItemsSource data binding. This ComboBox also listens for the SelectionChanged event.

However, when the ItemsSource changes, the SelectionChanged event occurs. This only happens when the ItemSource is a view.

Is there a way for SelectionChanged to increase only when the user does this, and not when the ItemsSource property changes?

+4
source share
2 answers

If you bind data to code behind, you can unsubscribe from SelectionChanged until the ItemSource is changed. Sample code below:

XAML:

<Window x:Class="WpfApplication1.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <StackPanel DataContextChanged="OnDataContextChanged"> <Button Content="Change items" Click="OnClick" /> <ComboBox Name="_cb" /> </StackPanel> </Window> 

Code behind:

 public partial class Window1 { public Window1() { InitializeComponent(); _cb.SelectionChanged += OnSelectionChanged; DataContext = new VM(); } private void OnClick(object sender, RoutedEventArgs e) { (DataContext as VM).UpdateItems(); } private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { } private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { VM vm = DataContext as VM; if (vm != null) { _cb.ItemsSource = vm.Items; vm.PropertyChanged += OnVMPropertyChanged; } else { _cb.ItemsSource = null; } } void OnVMPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "Items") { _cb.SelectionChanged -= OnSelectionChanged; _cb.ItemsSource = (DataContext as VM).Items; _cb.SelectionChanged += OnSelectionChanged; } } } public class VM : INotifyPropertyChanged { public VM() { UpdateItems(); } public event PropertyChangedEventHandler PropertyChanged; private List<string> _items = new List<string>(); public List<string> Items { get { return _items; } set { _items = value; if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs("Items")); } } } public void UpdateItems() { List<string> items = new List<string>(); for (int i = 0; i < 10; i++) { items.Add(_random.Next().ToString()); } Items = items; } private static Random _random = new Random(); } 
+3
source

I found this method:

 private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { if(!ComboBox.IsDropDownOpen) { return; } ///your code } 
+1
source

All Articles