[英]WPF-TreeView DataBinding in MVVM
我只是嘗試使用帶有DataBinding的WPF-TreeView實現簡單的MVVM模型。 但是我發現它存在一些問題,並希望你們中的某人可以幫助我。
我有模型,可以在這里定義自己的課程:
public class ItemOfWorld : INotifyPropertyChanged
{
#region Fields
private ObservableCollection<ItemOfWorld> _Items;
private string _Name;
private ItemOfWorld _Parent;
#endregion
#region FieldDeclaration
public ObservableCollection<ItemOfWorld> Items
{
get
{
return _Items;
}
set
{
_Items = value;
OnPropertyChanged("Items");
}
}
public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
OnPropertyChanged("Name");
}
}
public ItemOfWorld Parent
{
get
{
return _Parent;
}
set
{
_Parent = value;
OnPropertyChanged("Parent");
}
}
#endregion
public ItemOfWorld(ItemOfWorld parent)
{
Items = new ObservableCollection<ItemOfWorld>();
Parent = parent;
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
#endregion
}
public class MyWorld:ItemOfWorld
{
public MyWorld():base(null)
{
Name = "MyWorld";
Items.Add(new Ions(this));
}
}
public class Ions : ItemOfWorld
{
public Ions(ItemOfWorld parent)
: base(parent)
{
Name = "Ions";
Parent = parent;
}
}
public class Molecules : ItemOfWorld
{
public Molecules(ItemOfWorld parent)
: base(parent)
{
Name = "Molecules";
Parent = parent;
}
}
我有一個ViewModel,在其中創建MyWorld類:
internal class ItemsOfWorldViewModel
{
#region Fields
private ItemOfWorld _MyItem;
#endregion
#region FieldDeclaration
public ItemOfWorld MyItem
{
get
{
return _MyItem;
}
set
{
_MyItem = value;
}
}
#endregion
public ItemsOfWorldViewModel()
{
MyItem = new MyWorld();
}
}
最后,我有一個帶有TreeView的視圖工具箱,其中包含簡單的代碼:
ItemsOfWorldViewModel myworld=new ItemsOfWorldViewModel();
TreeView1.DataContext = myworld;
我的問題是:如何在不使用本地資源的情況下在TreeView中顯示層次結構?
-MyWorld
-->Ions
-->Molecules
如果我實現了簡單的TextBlock,則無需任何其他庫和本地源就可以工作,而在代碼隱藏和XAML中只需簡單的DataContext:
<TextBox x:Name="TextBlock2" Text="{Binding MyItem.Name}"></TextBox>
使用HierarchicalDataTemplate
作為TreeView.ItemTemplate
<TreeView ItemsSource="{Binding MyItem.Items}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:ItemOfWorld }" ItemsSource = "{Binding Path=Items}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.