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

3

5

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?

Unpeopled answered 10/2, 2011 at 5:17 Comment(0)
J
10

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

Joashus answered 10/2, 2011 at 5:20 Comment(2)
Ok! I change all IList and List to "ObservableCollection". Next, how do I notify user interface something in collection is changed? (Sorry, I'm new in WPF)Unpeopled
@user610801, just changing the collection type to ObservableCollection was enough for my WPF TreeView to update when I add/remove items from the colleciton.Neural
G
0

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.

Goneness answered 13/7, 2016 at 11:43 Comment(0)
C
0

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 }
          };
       } 
    }

 }
Crappie answered 30/4, 2019 at 7:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.