gpt4 book ai didi

c# - WPF TreeView-添加/删除节点后如何刷新树?

转载 作者:太空狗 更新时间:2023-10-30 00:57:33 25 4
gpt4 key购买 nike

我引用这篇文章:

WPF TreeView HierarchicalDataTemplate - binding to object with multiple child collections

并修改树结构,如:

Root
|__Group
|_Entry
|_Source

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

在 Source.cs 中:

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

在 XAML 文件中:

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

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

当我在特定节点“Entry”上单击右键以在 Entry 下添加一个新节点“Source”时(调用“Add”方法),我在Entry下成功添加了一个新的“Source”对象,但是在treeview上看不到这个新节点。如何在添加/删除节点时刷新 TreeView ?

最佳答案

使用ObservableCollection如果你想通知用户界面集合中的某些内容已更改,而不是 IList

关于c# - WPF TreeView-添加/删除节点后如何刷新树?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4953644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com