我有以下ViewModel类:
public class ViewModel : INotifyPropertyChanged
{
public ViewModel()
{
m_folders = new List<Folder>();
}
private List<Folder> m_folders;
public List<Folder> Folders
{
get { return m_folders; }
set
{
m_folders = value;
NotifiyPropertyChanged("Folders");
}
}
void NotifiyPropertyChanged(string property)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
public event PropertyChangedEventHandler PropertyChanged;
}
和Folder类:
public class Folder
{
public Folder()
{
Folders = new List<Folder>();
}
public string FullPath
{
get;
set;
}
public string FolderLabel
{
get;
set;
}
public List<Folder> Folders
{
get;
set;
}
}
ViewModel类被绑定到TreeView,如下所示:
<TreeView ItemsSource="{Binding Folders}" Margin="10" Height="200" Name="treeView">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Folders}" DataType="{x:Type local:Folder}" >
<TextBlock Text="{Binding FolderLabel}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
绑定本身在Window Load事件中完成,然后填充对象:
public ViewModel model = new ViewModel();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
treeView.DataContext = model;
//add Root items
model.Folders.Add(new Folder { FolderLabel = "Dummy1", FullPath = @"C:\dummy1" });
model.Folders.Add(new Folder { FolderLabel = "Dummy2", FullPath = @"C:\dummy2" });
model.Folders.Add(new Folder { FolderLabel = "Dummy3", FullPath = @"C:\dummy3" });
model.Folders.Add(new Folder { FolderLabel = "Dummy4", FullPath = @"C:\dummy4" });
//add sub items
model.Folders[0].Folders.Add(new Folder { FolderLabel = "Dummy11", FullPath = @"C:\dummy11" });
model.Folders[0].Folders.Add(new Folder { FolderLabel = "Dummy12", FullPath = @"C:\dummy12" });
model.Folders[0].Folders.Add(new Folder { FolderLabel = "Dummy13", FullPath = @"C:\dummy13" });
model.Folders[0].Folders.Add(new Folder { FolderLabel = "Dummy14", FullPath = @"C:\dummy14" });
model.Folders[0].Folders[0].Folders.Add(new Folder { FolderLabel = "MyDummy1", FullPath = @"xxxxxx" });
}
到目前为止,这么好。一切都很好。然后我向表单添加一个按钮,并从表单加载中删除填充代码并将其放在按钮单击上。它不起作用了。 TreeView绑定不再起作用。我做错了吗?
答案 0 :(得分:3)
因为您将TreeView的项目源绑定到List<Folder>
。初始绑定将起作用,但进一步的更新不会反映在UI中,因为List<T>
内部不实现INotifyPropertyChanged
和INotifyCollectionChanged
接口。您需要将List<Folder>
替换为ObservableCollection<Folder>
。