ComboBox.SourceUpdated event does not fire

I have two ComboBoxes in my view. Both are associated with two different ObservableCollections in the ViewModel, and when the selected item in ComboBox1 is changed, ComboBox2 is updated with a different collection. Binding works very well, however I want the second ComboBox to always select the first item in its collection. It initially works, however, when the source and elements in ComboBox2 are updated, the selection index changes to -1 (i.e., the first element is no longer selected).

To fix this, I added the SourceUpdated event to ComboBox2 and the method that the event causes the index to change back to 0. The problem is that the method never gets called (I put a breakpoint at the very top of the method and it doesn’t hit). Here is my XAML code:

 <Grid> <StackPanel DataContext="{StaticResource mainModel}" Orientation="Vertical"> <ComboBox ItemsSource="{Binding Path=FieldList}" DisplayMemberPath="FieldName" IsSynchronizedWithCurrentItem="True"/> <ComboBox Name="cmbSelector" Margin="0,10,0,0" ItemsSource="{Binding Path=CurrentSelectorList, NotifyOnSourceUpdated=True}" SourceUpdated="cmbSelector_SourceUpdated"> </ComboBox> </StackPanel> </Grid> 

And in the code:

 // This never gets called private void cmbSelector_SourceUpdated(object sender, DataTransferEventArgs e) { if (cmbSelector.HasItems) { cmbSelector.SelectedIndex = 0; } } 

Any help is appreciated.

+2
c # events data-binding wpf xaml
source share
1 answer

After working on it for an hour, I finally figured it out. The answer is based on this question: Listen for changes to the dependency property.

That way, you can define the Property changed event for any DependencyProperty object. This can be very useful when you need to extend or add additional events to a control without having to create a new type. The basic procedure is as follows:

 DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(ComboBox.ItemsSourceProperty, typeof(ComboBox)); descriptor.AddValueChanged(myComboBox, (sender, e) => { myComboBox.SelectedIndex = 0; }); 

This means that it creates a DependencyPropertyDescriptor object for the ComboBox.ItemsSource property, and then you can use this handle to register an event for any control of this type. In this case, every time the ItemsSource myComboBox property changes, the SelectedIndex property is set to 0 (this means that the first item in the list is selected.)

+3
source share

All Articles