我正在使用 ObservableDictionary 来绑定此树形结构(它具有 ICollectionChanged 事件)。结构如下:
ObservableDictionary<string,CustomClass> mainitems; public class CustomClass{ ObservableDictionary<string, InnerClass> sub1item; // 此类中有一堆属性和方法 // INotify 没有实现 } public class InnerClass{ // 此类中有一堆属性和方法 // INotify 没有实现 public SomeEnum Status{ get{ return this.status; } } }
上面提到的图形是使用自定义转换器绑定的,该转换器将 Status 枚举转换为路径,以便可以进行绑定(即 <img source="{Binding Path=something, Converter={StaticResource someconverter}, Mode=OneWay" /> )。
我的问题是,当我使用新状态更新 CustomClass 的 sub1item 字典时,它不会在 UI 中更新。我认为实现 INotify 可能有效,但我不知道需要在哪里更新它以及如何确切地执行。
编辑:我的树形视图的 XAML 模板如下:
<TreeView Name="tvInstance" ItemsSource="{Binding}" TreeViewItem.Selected="tviSelected" IsTextSearchEnabled="True">
<TreeView.ItemContainerStyle>
<Style>
<Setter Property="TreeViewItem.IsExpanded" Value="{Binding Path=Value.Expanded, Mode=TwoWay}" />
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Value.CustomClass}" ItemContainerStyle="{x:Null}">
<StackPanel Orientation="Horizontal">
<Label Content="{Binding Path=Key}"/>
</StackPanel>
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Path=Value.AnotherClass}">
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=Value.Status, Converter={StaticResource convertstatus} }"
Width="10" Height="10"/>
<Label Content="{Binding Path=Key}" />
</StackPanel>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=Value, Converter={StaticResource convertstatus} }"
Width="10" Height="10"/>
<Label Content="{Binding Path=Key}" />
</StackPanel>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
编辑:在我的主类、CustomClass 和 InnerClass 中添加所有 INotifyPropertyChanged 事件后,它仍然无法工作。我正在使用 ObservableDictionary 的 Dr. WPF 版本(由于我需要进行大量查找,所以使用字典非常重要)。请帮忙!
结语
这个页面上的答案是正确的,因为需要在 UI 中更新的属性上实现 INotifyPropertyChanged。
我发现绑定字典太麻烦了,所以我保留了 ObservableCollection 和 Dictionary。我使用字典进行查找,使用集合进行绑定(因为两者都使用对象的相同引用,使用集合很容易删除且只需 O(n) 操作)。
关于在 UI 中更新,请参考本页其他帖子。