【问题标题】:UI not updated on ObservableCollection changeUI 未在 ObservableCollection 更改时更新
【发布时间】:2014-01-01 06:52:33
【问题描述】:

我要完成以下任务:

使用CheckBoxes 显示资源(例如汽车、房间等)的TreeView 以选择项目或所有项目。

为此,我有一个 Dictionary<ResourceCategory, List<Resource>> 用作 TreeView's ItemsSource 和一个MultiBinding 用于CheckBoxesinside DataTemplate,其中一个绑定到资源的ID,另一个绑定到选定的资源ObservableCollection< Resource>

<TreeView Grid.Row="1" ItemsSource="{Binding Path=Category2ResourcesDictionary}" >
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Path=Value}">
                    <TextBlock Text="{Binding Path=Key}" />
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <CheckBox Content="{Binding}" PreviewMouseDown="RessourcenTV_OnClick">
                                <CheckBox.IsChecked>
                                    <MultiBinding Converter="{StaticResource CheckBoxConverter}" UpdateSourceTrigger="PropertyChanged" NotifyOnSourceUpdated="True">
                                        <Binding Path="ResourceId" Mode="OneWay" />
                                        <Binding Path="SelectedResources" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged" RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}" />
                                    </MultiBinding>
                                </CheckBox.IsChecked>
                            </CheckBox>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>

我的问题是,当我在后面的代码中将资源对象添加到选定的资源集合时,它的CheckBox 仍然未选中(未调用Convert 方法), 但所选资源集合包含它。

为什么CheckBox 仍未选中?

编辑: Add()Remove() 方法不起作用,但是当我分配一个新的 ObservableCollection 包含旧的选定资源集合加/减我想要添加/删除的那个时,它工作得很好。但是我也可以使用普通的List...

【问题讨论】:

    标签: c# wpf checkbox treeview observablecollection


    【解决方案1】:

    您的问题之一是您用作ItemsSourceDictionary 没有实现INotifyCollectionChanged 接口。另一个可能是您没有实现包含所有必需属性的INotifyPropertyChanged接口的特定数据类型类。

    要解决此问题,首先为实现INotifyPropertyChanged 接口的数据项定义适当的视图模型类,包括所有它需要的必需属性。然后,创建这些对象的 ObservableCollection 并将 that 绑定到 ListBox.ItemsSource 属性。然后,当您将项目添加到内部集合或进行任何属性更改时,您将看到 UI 更新如预期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-28
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      相关资源
      最近更新 更多