Reputation: 61
I just try to implement simple MVVM-model with WPF-TreeView with DataBinding. But I found some problems with it and hope, that someone of you can help me with it.
I have Model, where I defind my own class:
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;
}
}
I have a ViewModel, where I create MyWorld class:
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();
}
}
And, finally, I have a View with TreeView toolbox, with simple code-behind:
ItemsOfWorldViewModel myworld=new ItemsOfWorldViewModel();
TreeView1.DataContext = myworld;
My question is: How can I show in my TreeView my hierarchy without using local-sources?
-MyWorld
-->Ions
-->Molecules
If I implement simple TextBlock it is works without any additional libraries and local-sources, just simple DataContext in code-behind and in XAML:
<TextBox x:Name="TextBlock2" Text="{Binding MyItem.Name}"></TextBox>
Upvotes: 0
Views: 2473
Reputation: 18578
Use HierarchicalDataTemplate
as your 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>
Upvotes: 1