【问题标题】:why the converter is not running?为什么转换器不运行?
【发布时间】:2014-12-12 09:43:32
【问题描述】:

我正在使用 MVVM 模式,在我看来我有这个dataGrid

<Setter Property="Background">
    <Setter.Value>
        <MultiBinding Converter="{StaticResource myMultiValueConverter}">
            <MultiBinding.Bindings>
                <Binding />
                <Binding ElementName="ThisControl" Path="DataContext.MyObservableCollectionInViewModel"/>
                <Binding ElementName="thisControl" Path="DataContext.ControlType"/>
                <Binding ElementName="ThisControl" Path="DataContext.ExternalItems"/>
                <Binding Path="Componentes.OneProperty"/>
            </MultiBinding.Bindings>
        </MultiBinding>
    </Setter.Value>
</Setter>

我的视图模型有这个代码:

private void myMethod()
{
    MyObservableCollectionInViewModel.Clear();
    MyObservableCollectionViewModel.Add(new myType());
}

当我执行MyMethod()方法时,如果我没记错,多值转换器会运行,因为ObservableCollection在我添加或删除项目时实现INotifyPropertyChanged,但在这种情况下不起作用.

但是我的dataGridDataSource 有另一个ObservableCollection,它按预期工作,当我从ObservableCollection 添加或删除项目时刷新dataGrid

但是,如果在myMethod 我这样做:

private myMethod()
{
    myObservableCollectionInMyViewModel.Clear();
    myObservableCollectionInMyViewModel.Add(new MyType());
    myObservableCollectionInMyViewModel = new ObservableCollection(myObservableCollectionInMyViewModel);
}

它可以工作,所以当我创建一个新的ObservableCollection 时,视图会得到通知,而不是当我在实际的ObservableCollecion 中添加或删除项目时。

【问题讨论】:

    标签: c# mvvm datagrid observablecollection imultivalueconverter


    【解决方案1】:

    是的,这是正确的行为。

    ObservableCollection Add/Remove 适用于ItemsControlListBoxDataGrid 等的原因是它们明确处理您所描述的行为,这不是 WPF 特定的,例如:与ItemsSource的实际绑定无关。

    幕后发生的事情是,所有这些控件(ListBox 等)都继承自 ItemsControl,后者最终将 ItemsSource 包装成 CollectionView,这将利用 INotifyCollectionChanged 接口,如果可能的。这就是它知道/跟上的方式。

    我成功使用的“解决方法”:

    A) 只需使用已更改的属性或按照您所做的那样进行交换(这可能会或可能不起作用 - 我不完全记得,但 WPF 可能会明确检查实际值是否已更改,在此案例:它没有):

     myObservableCollectionInMyViewModel.Clear();
     myObservableCollectionInMyViewModel.Add(new MyType());
     RaisePropertyChanged(() => myObservableCollectionInMyViewModel);
    

    B)

    myObservableCollectionInMyViewModel = 
       new ObservableCollection(new List<MyType>{
          new MyType()});
    

    C) 与 .Count 绑定,因为 ObservableCollection 将在更改时通知。

         <Binding ElementName="ThisControl" 
    Path="DataContext.MyObservableCollectionInViewModel.Count"/
    

    D) 创建一个能够监听所有事件(INotifyPropertyChanged 和 INotifyCollectionChanged)事件的新转换器,然后触发多转换器更新。

    <Binding ElementName="ThisControl" 
       Converter="{StaticResource observableConverter}"
       Path="DataContext.MyObservableCollectionInViewModel"/>
    

    【讨论】:

      猜你喜欢
      • 2011-10-10
      • 2017-07-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-13
      • 1970-01-01
      • 2021-12-20
      • 1970-01-01
      相关资源
      最近更新 更多