2
我有一个具有分层数据模板(2级)的TreeView。我有一个在3级树视图的第一级创建的上下文菜单。我想将我的视图模型的命令绑定到上下文菜单的第二层。不幸的是,我只能在我的模型中使用命令时才能使用它,这不是我想要做的事情......如果可能,我希望在XAML中完成这一切。上下文菜单中子菜单项的命令绑定
我测试了纯粹的xaml解决方案here和here。 在设计器中,“标记”用蓝色下划线表示
"Cannot resolve Property Tag in data context of type System.Windows.UIElement",或者如果我使用“Parent.PlacementTarget ....”,设计者告诉我 代码是可编译的,但我的命令永远不会到达。
这是我有:
在ResourceDictionary中:
<DataTemplate DataType="{x:Type viewModel:UpdateToolViewModel}">
<view:UpdateToolView/>
</DataTemplate>
<DataTemplate x:Key="ToolNameDataTemplate" DataType="{x:Type src:Element}">
<Grid>
<TextBlock Text="{Binding Path=NameProperty.Value}" FontSize="12" />
</Grid>
</DataTemplate>
<HierarchicalDataTemplate x:Key="ToolGroupsDataTemplate" ItemsSource="{Binding Elements}" DataType="{x:Type src:ElementGroup}" ItemTemplate="{StaticResource ToolNameDataTemplate}">
<TextBlock Text="{Binding Path=TextProperty.Value}" FontSize="14" FontWeight="Bold" Tag="{Binding ElementName=UpdateToolControl}">
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Add Tool" ItemContainerStyle="{StaticResource ToolGroupContextMenuToolsItemStyle}" >
<MenuItem.ItemsSource>
<CompositeCollection>
<MenuItem Header="Add New ..." Command="{Binding PlacementTarget.Tag.DataContext.AddToolCommand, RelativeSource={RelativeSource FindAncestor, AncestorType=ContextMenu}}" />
<CollectionContainer Collection="{Binding Source={StaticResource AddToolContextMenuSource}}"/>
</CompositeCollection>
</MenuItem.ItemsSource>
</MenuItem>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</HierarchicalDataTemplate>
在用户控件:
<UserControl x:Class="...UpdateToolView" ... Name="UpdateToolControl">
<TreeView Name="ToolTreeView" ItemsSource="{Binding AllElementsInGroups}"
ItemTemplate="{StaticResource ToolGroupsDataTemplate}"
ItemContainerStyle="{StaticResource ToolTreeViewItemStyle}"/>
</UserControl>
我已经在我的模型中使用该命令的边缘,在我的视图模型中调用一个方法。不好,但我似乎没有让它工作不同。
另外你可以做的是将你的'ContextMenu'的定义移动到'UserControl'。然后你的上下文菜单将有你的'UserControl'的数据上下文,我认为它是你的'ViewModel'。请记住:'ContextMenu'不是Visual Tree的一部分。 HTH – XAMlMAX
使用'ResourceDictionaries',我尽量保持xaml代码的清洁和结构。我的UserControl包含了比上面例子中所示更多的xaml。但我会记住你的评论。谢谢你。 – SBa