public class TreeNode
{
public int ParentId { get; set; }
public string Name { get; set; }
public ObservableCollection<TreeNode> Children { get; set; }
}
public class TreeViewModel
{
public ObservableCollection<TreeNode> Nodes { get; set; }
public TreeNode SelectedNode { get; set; }
}
public partial class MainWindow : Window
{
public TreeViewModel model { get; set; }
private int i = 1;
public MainWindow()
{
InitializeComponent();
model = new TreeViewModel();
model.Nodes = new ObservableCollection<TreeNode>();
this.DataContext = model;
model.Nodes.Add(new TreeNode() { Name = "Root", Children = new ObservableCollection<TreeNode>() });
model.Nodes.FirstOrDefault().Children.Add(new TreeNode() { Name = "Second" });
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if (model.SelectedNode != null)
{
model.SelectedNode.Children.Add(new TreeNode() { Name = "Children "+i.ToString(), Children = new ObservableCollection<TreeNode>() });
}
else
{
model.Nodes.Add(new TreeNode() { Name = "Root "+i.ToString(), Children = new ObservableCollection<TreeNode>() });
}
i++;
}
private void TreeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
{
model.SelectedNode = (TreeNode)e.NewValue;
}
}
<Grid>
<TreeView HorizontalAlignment="Left" Height="337" Margin="42,34,0,0" VerticalAlignment="Top" Width="303" ItemsSource="{Binding Path=Nodes}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
<Button Content="Button" HorizontalAlignment="Left" Margin="374,34,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
1. Использовать для привязываемых коллекций - ObservableCollection - умеет оповещать подписчика об изменении коллекции
2. WPF не умеет привязывает SelectedItem у TreeView, решения-
https://stackoverflow.com/questions/7153813/wpf-mv... ,
https://tyrrrz.me/blog/wpf-treeview-selecteditem-t...