在我的WPF应用程序中,我想添加一个TreeView控件。树视图控件需要使用数据库中的项填充。所以我将ItemsSource属性绑定到字符串集合。
树控件中的每个项目都可以包含0到32个子项。同样,这些项目需要绑定。这些子项中的每一个都应该有一个上下文菜单,其中包含两个选项“重命名”和“删除”。我怎么能在WPF中做到这一点?
答案 0 :(得分:4)
有几种方法可以做到这一点。这是使用绑定到基础视图模型上的属性IsLeaf
的触发器应用上下文菜单的一种方法。
MainWindow.xaml:
<Window x:Class="WpfScratch.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Window.Resources>
<!-- the context menu for all tree view items -->
<ContextMenu x:Key="TreeViewItemContextMenu">
<MenuItem Header="Rename" />
<MenuItem Header="Delete" />
</ContextMenu>
<!-- the data template for all tree view items -->
<HierarchicalDataTemplate x:Key="TreeViewItemTemplate" ItemsSource="{Binding Nodes}">
<TextBlock x:Name="TextBlock" Text="{Binding Text}" />
<HierarchicalDataTemplate.Triggers>
<DataTrigger Binding="{Binding IsLeaf}" Value="True">
<Setter TargetName="TextBlock" Property="ContextMenu" Value="{StaticResource TreeViewItemContextMenu}" />
</DataTrigger>
</HierarchicalDataTemplate.Triggers>
</HierarchicalDataTemplate>
</Window.Resources>
<!-- the treeview -->
<TreeView DataContext="{Binding TreeView}"
ItemsSource="{Binding Nodes}"
ItemTemplate="{StaticResource TreeViewItemTemplate}">
</TreeView>
</Window>
MainWindow.xaml.cs:
public partial class MainWindow
{
public MainWindow()
{
InitializeComponent();
DataContext = new MainWindowModel(
new MainWindowTreeViewModel(
new MainWindowTreeViewNodeModel(
"1",
new MainWindowTreeViewNodeModel("A"),
new MainWindowTreeViewNodeModel("B"),
new MainWindowTreeViewNodeModel("C")),
new MainWindowTreeViewNodeModel(
"2",
new MainWindowTreeViewNodeModel("A"),
new MainWindowTreeViewNodeModel("B"),
new MainWindowTreeViewNodeModel("C")),
new MainWindowTreeViewNodeModel(
"3",
new MainWindowTreeViewNodeModel("A"),
new MainWindowTreeViewNodeModel("B"),
new MainWindowTreeViewNodeModel("C"))));
}
}
MainWindowModel.cs:
public class MainWindowModel
{
public MainWindowModel(MainWindowTreeViewModel treeView)
{
TreeView = treeView;
}
public MainWindowTreeViewModel TreeView { get; private set; }
}
public class MainWindowTreeViewModel
{
public MainWindowTreeViewModel(params MainWindowTreeViewNodeModel[] nodes)
{
Nodes = nodes.ToList().AsReadOnly();
}
public ReadOnlyCollection<MainWindowTreeViewNodeModel> Nodes { get; private set; }
}
public class MainWindowTreeViewNodeModel
{
public MainWindowTreeViewNodeModel(string text, params MainWindowTreeViewNodeModel[] nodes)
{
Text = text;
Nodes = nodes.ToList().AsReadOnly();
}
public string Text { get; private set; }
public ReadOnlyCollection<MainWindowTreeViewNodeModel> Nodes { get; private set; }
public bool IsLeaf { get { return Nodes.Count == 0; } }
}