【发布时间】:2019-11-21 07:45:13
【问题描述】:
我有一个从ObservableCollection 派生的特定集合,我绑定到ItemSource 的ComboBox 的这种类型的集合。问题是,当ItemSource 更改时,SelectedItem 被破坏了,所以我需要连接ItemSource 更改的事件,以便我可以手动设置SelectedItem 属性。
我曾尝试使用IsSynchronizedWithCurrentItem="True",但这会导致从列表中选择第一个项目,在我的情况下这不是我想要的,因为SelectedItem 不是列表中的第一个。我创建了一个Behavior 并附加到ComboBox 但我找不到一个事件来连接ItemSource 更改,我也不能依赖 ObservableCollection 的属性更改,因为在大多数情况下,Collection 对项目有更改在列表中,并且没有添加或删除新项目。我将在我的实现下方发布。
<ComboBox ItemsSource="{Binding DisplayZoneNumberSource}"
SelectedItem="{Binding DisplayZoneNumberSelect, UpdateSourceTrigger=PropertyChanged}"
ItemTemplateSelector="{StaticResource ComboBoxSourceTemplateSelector}"
VerticalContentAlignment="Center">
<i:Interaction.Behaviors>
<local:ComboBoxItemSourceChangedBehavior/>
</i:Interaction.Behaviors>
</ComboBox>
public class ComboBoxItemSourceChangedBehavior : Behavior<ComboBox>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.SelectionChanged += AssociatedObject_SelectionChanged;
}
protected override void OnDetaching()
{
base.OnDetaching();
AssociatedObject.SelectionChanged -= AssociatedObject_SelectionChanged;
}
private static void AssociatedObject_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//Implementation
}
}
【问题讨论】:
-
“当
ItemSource被改变时SelectedItem被毁了”->你是什么意思? -
您的实际问题是什么?
-
如何捕获 ItemSource 更改事件