WPF TreeView-How to refresh tree after adding/removing node?

18.5k views Asked by At

I refer to this article:

WPF TreeView HierarchicalDataTemplate - binding to object with multiple child collections

and modify the tree structure like:

Root
  |__Group
       |_Entry
           |_Source

In Entry.cs:

public class Entry
{
    public int Key { get; set; }
    public string Name { get; set; }

    public ObservableCollection<Source> Sources { get; set; }

    public Entry()
    {
        Sources = new ObservableCollection<Source>();
    }

    public ObservableCollection<object> Items
    {
        get
        {
            ObservableCollection<object> childNodes = new ObservableCollection<object>();

            foreach (var source in this.Sources)
                childNodes.Add(source);

            return childNodes;
        }
    }
}

In Source.cs:

public class Source
{
    public int Key { get; set; }
    public string Name { get; set; }
}

In XAML file:

<UserControl.CommandBindings>
    <CommandBinding Command="New" Executed="Add" />
</UserControl.CommandBindings>

    <TreeView x:Name="TreeView">
        <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="TreeViewItem.IsExpanded" Value="True"/>
            </Style>
        </TreeView.ItemContainerStyle>

        <TreeView.Resources>
            <HierarchicalDataTemplate DataType="{x:Type local:Root}" ItemsSource="{Binding Items}">
                 <TextBlock Text="{Binding Path=Name}" IsEnabled="True">
                 </TextBlock>
            </HierarchicalDataTemplate>

            <HierarchicalDataTemplate DataType="{x:Type local:Group}" ItemsSource="{Binding Items}">
                <TextBlock Text="{Binding Path=Name}" IsEnabled="True">
                </TextBlock>
            </HierarchicalDataTemplate>


            <HierarchicalDataTemplate DataType="{x:Type local:Entry}" ItemsSource="{Binding Items}">
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Path=Name}" IsEnabled="True">
                        <TextBlock.ContextMenu>
                            <ContextMenu >
                                <MenuItem Header="Add" Command="New">
                                </MenuItem>
                            </ContextMenu>
                        </TextBlock.ContextMenu>
                    </TextBlock>
                </StackPanel>
            </HierarchicalDataTemplate>


            <DataTemplate DataType="{x:Type local:Source}" >
                <TextBlock Text="{Binding Path=Name}" />
            </DataTemplate>

        </TreeView.Resources>
    </TreeView>

In UserControl.cs:

public ObservableCollection<Root> Roots = new ObservableCollection<Root>();

    public UserControl6()
    {
        InitializeComponent();

        //...Add new node manually

        TreeView.ItemsSource = Roots;
    }

    private void Add(object sender, ExecutedRoutedEventArgs e)
    {
        Entry ee = (Entry)TreeView.SelectedItem;
        Source s3 = new Source() { Key = 3, Name = "New Source" };
        ee.Sources.Add(s3);
    }

When I click right button on specific node "Entry" to add a new node "Source" under Entry (call "Add" method), I add a new "Source" object under Entry successfully, but I can't see this new node on treeview. How to refresh treeview when adding/deleting node?

3

There are 3 answers

2
Arsen Mkrtchyan On BEST ANSWER

Use ObservableCollection instead of IList if you want to notify the user interface that something in the collection has changed

0
xyzWty On

Use this class and any changes in Sources collection will update/refresh tree in UI.

public class Entry
{
    public int Key { get; set; }
    public string Name { get; set; }

    public ObservableCollection<Source> Sources { get; set; }

    public Entry()
    {
        Sources = new ObservableCollection<Source>();
    }

    public CompositeCollection Items
    {
       get
       {
          return new CompositeCollection()
          {
             new CollectionContainer() { Collection = Sources },
             // Add other type of collection in composite collection
             // new CollectionContainer() { Collection = OtherTypeSources }
          };
       } 
    }

 }
0
Mr.B On

As far as I'm concerned, changing of type for Items to ObservableCollection<T> will not resolve the problem. You need to implement INotifyPropertyChanged. I tested both solutions for my tree view, because I faced the same problem. In my case changing of type from IList to ObservableCollection didn't refreshed GUI. However when I changed my auto property:

public List<SourceControlItemViewBaseModel> Items { get; set; }

to

 private IEnumerable<SourceControlItemViewBaseModel> _items;
    public IEnumerable<SourceControlItemViewBaseModel> Items
    {
        get { return _items; }
        set
        {
            _items = value;
            OnPropertyChanged();
        }
    }

Namely, I've implemented INotifyPropertyChanged and that changed the situation. The method that builds the tree structure defines the actual type of Items as new List<T>(), but it works and refreshes the GUI . Nevertheless my tree was built in pure MVVM pattern without usage code-behind. I use

<TreeView ItemsSource="{Binding SourceControlStructureItems}" />

and in the view model I use:

  currentVm.Items= await SourceControlRepository.Instance.BuildSourceControlStructureAsync(currentVm.ServerPath);

That means I didn't added/removed items, but I rebuilt Node's sub collection.