我的视图中有两个ComboBox。它们都绑定到ViewModel中的两个不同的ObservableCollections
,并且当ComboBox1中的选定项更改时,ComboBox2将使用不同的集合进行更新。绑定工作正常,但是,我希望第二个ComboBox始终选择其集合中的第一个项目。最初,它可以工作,当ComboBox2中的源和项目更新时,选择索引变为-1(即不再选择第一个项目)。
为了解决这个问题,我向ComboBox2添加了一个SourceUpdated
事件,并且事件调用的方法将索引更改回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;
}
}
感谢任何帮助。
答案 0 :(得分:3)
经过一个小时的努力,我终于明白了。答案基于这个问题:Listen to changes of dependency property.
所以基本上你可以为对象上的任何DependencyProperty
定义一个“Property Changed”事件。当您需要向控件扩展或添加其他事件而不必创建新类型时,这非常有用。基本程序是这样的:
DependencyPropertyDescriptor descriptor =
DependencyPropertyDescriptor.FromProperty(ComboBox.ItemsSourceProperty, typeof(ComboBox));
descriptor.AddValueChanged(myComboBox, (sender, e) =>
{
myComboBox.SelectedIndex = 0;
});
这样做是为DependencyPropertyDescriptor
属性创建一个ComboBox.ItemsSource
对象,然后您可以使用该描述符为该类型的任何控件注册一个事件。在这种情况下,每次更改ItemsSource
的{{1}}属性时,myComboBox
属性都会设置回0(这意味着列表中的第一项被选中。)