0

我有一个从 ComboBox 派生的自定义控件,我在其中使用 CompositeCollection 将原始 ItemsSource 与其他对象“合并”。

问题是,那

CompositeCollection comp = new CompositeCollection();
SomeLogic();
ItemsSource = comp;

将 ItemsSource 设置为组合 Collection 就是将 SelectedItem 设置为 null 并调用 Binding TwoWay Binding 到 ViewModel。然后,我的 ViewModel 中的 SelectedItem 绑定属性将为“null”。

我目前正在通过在分配 ItemsSource 后恢复 SelectedItem 来解决此问题:

 Object priorSelectedItem = SelectedItem;
 ItemsSource = comp;    
 SelectedItem = priorSelectedItem;

然而,这只是修复了我的 ViewModel 中 SelectedItem 的值,一个令人讨厌的副作用是,当对象更改时,某些逻辑在 Setter 中运行。EG设置一个

_dataHasChanged = true; 

旗帜。

所以如果有什么办法我可以

a) 防止 SelectedItem 在更改 ItemsSource 时重置

或者

b) 防止在更改 ItemsSource 时调用 SelectedItem-Binding

从自定义控件中(不想处理 20 个 ViewModel,因为控件中存在缺陷)我将非常感谢有关如何执行此操作的任何输入 :-)

4

1 回答 1

0

通过将 SelectedItem-Binding 保存在 OnApplyTemplate() 的私有变量中,然后在应用新的 ItemsSource 后将其清除并设置回变量值,我设法防止了这种行为。

    private Binding _selectedItemBinding;
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();

        _selectedItemBinding = BindingOperations.GetBinding(this, ComboBox.SelectedItemProperty);
        BindingOperations.ClearBinding(this, ComboBox.SelectedItemProperty);
        if (BindingOperations.IsDataBound(this, ComboBox.SelectedItemProperty))
            this.SetBinding(ComboBox.SelectedItemProperty, "dummy");
        ...
    }

 private void AdaptItemSource()
 {
   Object priorSelectedItem = SelectedItem;
   ItemsSource = comp;    
   SelectedItem = priorSelectedItem;

   BindingOperations.SetBinding(this, ComboBox.SelectedItemProperty, _selectedItemBinding);
 }

这对我有用

于 2012-11-16T12:37:21.263 回答