【发布时间】:2009-06-16 15:27:31
【问题描述】:
我有一个 3 层深的树视图,
-主要的 ->:SUB1 >:SUB2 >:SUB2 -X:SUB1 X:SUB2 SUB1 SUB1其中,> 和 X 表示表示特定项目状态的图形(由后端确定)。
我正在使用 Observable Dictionary 绑定到这棵树(并且它有一个 ICollectionChanged 事件)。结构是这样的:
ObservableDictionary<string,CustomClass> mainitems;
public class CustomClass{
ObservableDictionary<string, InnerClass> sub1item;
// Bunch of properties and methods in this class
// INotify not implemented
}
public class InnerClass{
// Bunch of properties and methods in this class
// INotify not implemented
public SomeEnum Status{
get{ return this.status; }
}
}
上面提到的图形是使用自定义转换器绑定的,该转换器将状态枚举转换为路径以便可以绑定(即。)。
问题:
我的问题是,当我用新状态更新 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 中添加所有 INotifyProperty 事件后,它仍然不起作用。我正在使用 ObservableDictionary 的 Dr. WPF 版本(并且使用字典对我的应用程序至关重要,因为我需要进行大量查找)。救命!
结语
此页面中的答案是正确的,因为我需要在 UI 中更新的属性上实现 INotifyPropertyChanged。
我发现绑定字典太麻烦了,所以我同时保留了 ObservableCollection 和字典。我使用字典进行查找,使用集合进行绑定(因为两者都使用对对象的相同引用,所以使用集合和唯一的 O(n) 操作很容易删除)。
关于UI的更新,请参考本页其他帖子。
【问题讨论】:
-
您是否要重新实例化 sub1item 字典?如果是这样,那么您需要在包含它的类中实现 INotifyPropertyChanged。
-
CustomClass 有一个 Refresh() 方法设置 sub1item = new ObservableDictionary<..>();然后再次获取所有 InnerClass 项目。但是,它们几乎是相同的项目。我只想更新那些被改变的。 IE。渗透变化。
-
你有没有找到解决这个问题的方法?
-
赞成,因为您花时间写了那篇尾声。高五
标签: c# wpf data-binding