【发布时间】:2016-07-19 05:55:55
【问题描述】:
我正在使用 Explorer 树视图(我设计的自定义 wpf 控件)。我在 Generic.xaml:
中有这段代码<Style TargetType="{x:Type local:ExplorerControl}">
<Setter Property="Template" >
<Setter.Value>
<ControlTemplate TargetType="{x:Type local:ExplorerControl}">
<Border>
<TreeView Name="myTreeView" >
<TreeView.ItemContainerStyle>
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<MenuItem x:Name="myTemplate" Header="Remove" Command="{TemplateBinding RemoveCommand}"></MenuItem>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Nodes}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding Name}" VerticalAlignment="Center" />
</StackPanel>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
在 ExplorerControl 我有我的依赖属性:
public class ExplorerControl : Control{
public ExplorerControl()
{
Nodes = new ObservableCollection<Node>();
}
private ObservableCollection<Node> Nodes { get; }
public ICommand RemoveCommand
{
get { return (ICommand)GetValue(RemovedCommandProperty); }
set { SetValue(RemovedCommandProperty, value); }
}
public static readonly DependencyProperty RemovedCommandProperty =
DependencyProperty.Register("RemoveCommand", typeof(ICommand), typeof(ExplorerControl));
}
节点类
public class Node {
public string Name {get;set;}
}
我的问题是我不知道如何让 MenuItem 命令起作用
我试过这些:
- 如果我在 TreeView 之后使用带有按钮的相同代码(两者都在 Stackpanel 中),它可以工作。所以我认为问题在于 MenuItem DataContext
- 我尝试更改 MenuItem DataContext 但没有成功。
我希望你能帮助我。
编辑:我删除了关于DataContext的部分代码。谢谢你的回答。
我在我的 MainView 中使用这个控件:
<treeViewExplorerControl:ExplorerControl
SelectedItemName="{Binding SelectedItemName}"
SelectedItemPath="{Binding SelectedItemPath}"
RemoveCommand="{Binding ExplorerControlItemRemovedCommand}"/>
【问题讨论】:
-
请注意,将 ExplorerControl 设置为 TreeView.DataContext 会创建一个新的 ExplorerControl 实例。这没有任何意义。
-
@Clemens 谢谢我对自定义控件有点陌生。我删除了那部分代码。
-
是窗口中的最后一段代码吗?我不知道您的解决方案如何复制它。
-
@AzzamAziz 我有两个项目,一个是名为 treeViewExplorerControl 的自定义控件,另一个是 WPF 项目,在我的 MainView.xaml 中使用的 WPF 项目中的 ExplorerControl 和最后一段代码。
标签: c# wpf data-binding