Tell me how to make the removal of the selected item from the TreeView? (not at the top level)

As I understand it - you need to somehow get the parent of the element?

XAML for TreeView:

<TreeView x:Name="PrjTreeViev"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Path=Elems}"> <TextBlock Text="{Binding Name}" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> 

Binds to:

 ObservableCollection<TreeElem> tree_contents; //элементы TreeView для отображения PrjTreeViev.ItemsSource = tree_contents; ... public class TreeElem //класс с списком для отображения { public string Name { get; set; } public ObservableCollection<TreeElem> Elems { get; set; } } 
  • What should happen before an item needs to be deleted? - Ev_Hyper
  • one
    The usual solution is to populate a TreeView by binding to a collection of VM elements. In this case, to remove an item, simply remove it from the collection. - VladD
  • @VladD, And how to understand from which collection to delete an item? After all, each element can have its own collection of child elements. Just sort through everything? - trydex
  • one
    Well, you have the item itself. Suppose that an element contains, for example, a reference to the parent element. Then you need to delete from the parent element. - VladD
  • Yes, I wanted to do so. BUT unless such code will work correctly? It turns out we need to add the reference to Yourself inside the child elements of the CurrentItem? - trancer1019

2 answers 2

I will make an example using the Catel MVVM pattern.

XAML:

 <TreeView x:Name="PrjTreeViev" SelectedItem="{Binding SelectedItemTreeView}" ItemsSource="{Binding TreeViewSource, IsAsync=True}"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding Path=Elems}"> <TextBlock Text="{Binding Name}" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> 

Now let's go to the ViewModel code

C #

 /// <summary> /// Регистрируем TreeViewSourceProperty /// </summary> public static readonly PropertyData TreeViewSourceProperty = RegisterProperty("TreeViewSource", typeof(List<TreeElem>)); /// <summary> /// Установка, получение значений из TreeViewSource /// </summary> public List<TreeElem> TreeViewSource { get { return GetValue<List<TreeElem>>(TreeViewSourceProperty); } set { SetValue(TreeViewSourceProperty, value); } } /// <summary> /// Регистрируем SelectedItemTreeViewProperty /// </summary> public static readonly PropertyData SelectedItemTreeViewProperty = RegisterProperty("SelectedItemTreeView", typeof(TreeElem)); /// <summary> /// Установка, получение значений из SelectedItemTreeView /// </summary> public TreeElem SelectedItemTreeView { get { return GetValue<TreeElem>(SelectedItemTreeViewProperty); } set { SetValue(SelectedItemTreeViewProperty, value); } } public class TreeElem //класс с списком для отображения { public string Name { get; set; } public ObservableCollection<TreeElem> Elems { get; set; } } 

We will also make a command for deletion, which will be unavailable if no item is selected.

 public ICatelCommand DeletSelectedNode => new TaskCommand<TreeElem>(node => Task.Run(() => { if(MessageBox.Show($"Уверены что хотите удалить данный элмент {node.Name}?", "Подтвердите действие", MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes) TreeViewSource.Remove(node); /// Удаляем, если пользователь согласился }), node => SelectedItemTreeView != null); /// Команда не будет доступна если не выбран элемент в TreeView 

After all these operations we create a button, or a context menu, in which we create a binding on our team.

XAML:

 <Button Command="{Binding DeletSeletedNode}" CommandParametr="{Binding ElementName=PrjTreeViev, Path=SelectedItem}", Content="Удалить элемент"> 
  • Somewhere there may be errors as everything was written by hand, without any editors. - LLENN

Create a property

 public TreeElem SelectedTreeElem { get; set; } 

tie it

 <TreeView x:Name="PrjTreeViev" ItemsSource="{Binding tree_contents}" SelectedItem="{Binding SelectedTreeElem}"> 

Then the selected item can be deleted so

 //тут прежде надо на null проверить SelectedTreeElem tree_contents.Remove(SelectedTreeElem); SelectedTreeElem = null;