【发布时间】:2016-06-04 22:22:46
【问题描述】:
我有一个带有分层数据模板(2 级)的 TreeView。我在树视图的第一级创建了一个上下文菜单,有 3 个级别。我想将我的视图模型的命令绑定到上下文菜单的第二级。不幸的是,我只能在我的模型中使用命令时才能让它工作,这不是我想要做的......如果可能的话,我想在 XAML 中完成这一切。
我已经测试了给定here 和here 的纯xaml 解决方案。 在设计器中,“Tag”带有下划线的蓝色表示
“无法解析 System.Windows.UIElement 类型的数据上下文中的属性标签”或者,如果我使用“Parent.PlacementTarget....”,设计人员告诉我无法解析
PlacementTarget在 System.Windows.DependencyObject 类型的数据上下文中。代码是可编译的,但我的命令永远无法到达。
这就是我所拥有的:
在资源字典中:
<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不是可视树的一部分。 HTH -
使用
ResourceDictionaries,我尽量保持xaml 代码的简洁和结构化。我的UserControl包含的 xaml 比上面示例中显示的要多得多。但我会记住你的评论。谢谢你。
标签: wpf xaml mvvm commandbinding