[英]Do Hierarchical Data Template need INotifyPropertyChanged on property's property of observable collection type
我有一個簡單的例子,其背后的代碼是這樣的
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows;
namespace WpfApplication7
{
/// <summary>
/// Логика взаимодействия для MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public ObservableCollection<Item> Items { get; set; }
public MainWindow()
{
Items = new ObservableCollection<Item>();
InitializeComponent();
}
private void ButtonBase1_OnClick(object sender, RoutedEventArgs e)
{
Items.Add(new Item() { ItemName = DateTime.Now.ToString(), SubItems = new ObservableCollection<string>() {"1"} });
}
private void ButtonBase2_OnClick(object sender, RoutedEventArgs e)
{
var f = Items.FirstOrDefault();
if (f!=null)
f.SubItems.Add(f.SubItems.Count.ToString());
}
}
public class Item
{
public string ItemName { get; set; }
public ObservableCollection<string> SubItems { get; set; }
}
}
和XAML是這樣的
<Window x:Class="WpfApplication7.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApplication7"
mc:Ignorable="d"
Title="MainWindow" Height="350" Width="525" DataContext="{Binding RelativeSource={RelativeSource Self}}">
<StackPanel>
<TreeView ItemsSource="{Binding Path=Items}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubItems}">
<TextBlock Text="{Binding ItemName}"></TextBlock>
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"></TextBlock>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<ListBox ItemsSource="{Binding Path=Items}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding ItemName}"></TextBlock>
<ListBox ItemsSource="{Binding SubItems}">
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding}"></TextBlock>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button Click="ButtonBase1_OnClick">321</Button>
<Button Click="ButtonBase2_OnClick">123</Button>
</StackPanel>
</Window>
我仍然不清楚為什么行為不同 - ListBoxes隨着兩個集合中的每一個小變化而更新(如ObservableCollection所假設的)。 但是在TreeView中,只有第一級才能正確更新,而子級則不斷地是emty 。 如果我將INotifyPropertyChanged添加到SubItems屬性,TreeView的子級也會正確更新。 任何人都可以告訴我這件事嗎?
窗口打開后,它開始處理Items
集合中的所有數據。 完成后,對於窗口的項目更改,某些通知無法分開,以查看數據已更改且內容將更新。 所以,在這里尋求幫助的是INotifyPropertyChanged
及其堂兄INotifyCollectionChanged
。
您也可以考慮重置ListBox。 ItemsSource
為null並返回Items - 這將有效地使控件重新處理數據並重新呈現內容。
在VS2015上再次檢查VS2013,不能重復說明中的問題。 假設它是一些外部條件,而不是代碼。 無論如何,感謝@AlexSeleznyov的談話=)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.