ComboBox.SourceUpdated事件没有被解雇

问题描述:

我在我的视图中有两个组合框。它们都绑定到ViewModel中的两个不同的ObservableCollections,并且当ComboBox1中的所选项目发生更改时,ComboBox2会使用不同的集合进行更新。绑定工作得很好,但是,我希望第二个ComboBox始终选择其集合中的第一个项目。但是,最初它起作用,但是,当ComboBox2中的源和项目更新时,选择索引将更改为-1(即,不再选择第一个项目)。ComboBox.SourceUpdated事件没有被解雇

为了解决这个问题,我添加了一个SourceUpdated事件到ComboBox2和事件调用的方法,将索引更改为0.问题是该方法从未被调用(我在方法的最顶部放置了一个断点,并且它不会被击中)。这是我的XAML代码:

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

而在后台代码:

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

任何帮助表示赞赏。

工作了一个小时后,我终于明白了。答案基于这个问题:Listen to changes of dependency property.

所以基本上你可以定义一个“Property Changed”事件对任何DependencyProperty对象。当您需要将其他事件扩展或添加到控件而无需创建新类型时,这可能非常有用。基本程序是这样的:

DependencyPropertyDescriptor descriptor = 
    DependencyPropertyDescriptor.FromProperty(ComboBox.ItemsSourceProperty, typeof(ComboBox)); 

descriptor.AddValueChanged(myComboBox, (sender, e) => 
{ 
    myComboBox.SelectedIndex = 0; 
}); 

这里做的事情是,它创建ComboBox.ItemsSource属性DependencyPropertyDescriptor对象,然后你可以使用该描述符来为该类型的任何控制寄存器的事件。在这种情况下,每当myComboBoxItemsSource属性发生更改时,SelectedIndex属性设置回0(这意味着列表中的第一项被选中。)