【问题标题】:WPF ComboBox event for ItemSource changedItemSource 的 WPF ComboBox 事件已更改
【发布时间】:2019-11-21 07:45:13
【问题描述】:

我有一个从ObservableCollection 派生的特定集合,我绑定到ItemSourceComboBox 的这种类型的集合。问题是,当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
    }
}

【问题讨论】:

标签: c# wpf


【解决方案1】:

如果您创建一个继承自 ComboBox 的自定义类,则可以覆盖 protected OnItemsSourceChanged 方法:

public class MyComboBox : ComboBox
{
    protected override void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
    {
        base.OnItemsSourceChanged(oldValue, newValue);
        //...
    }
}

显然,当源集合中单个项目的属性被设置时,该方法不会被调用。如果您需要这样做,您需要为每个项目的PropertyChanged 连接一个事件处理程序,只要将项目添加到源集合或从源集合中删除。这需要您的项目类型实现INotifyPropertyChanged 或其他具有类似事件的接口。

【讨论】:

  • 有像OnItemsSourceChanging这样的事件吗?因为我不能使用答案中的那个,因为太晚了,SelectedItem 已经为空
猜你喜欢
  • 2013-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多