【发布时间】:2015-06-17 13:45:34
【问题描述】:
给定一个包含上下文菜单和控件模板的包含 MVVM 模式的用户控件,如何从上下文菜单中引用样式中的元素?以下代码似乎可以正常工作,但 MenuItem CommandParameter 除外。 “Template.MyViewBox.Child”的绑定路径显然不起作用,但展示了我想要完成的意图。
<UserControl x:Class="MyViewer.Views.IconView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:vm="clr-namespace:MyViewer.ViewModels">
<UserControl.Resources>
<vm:ViewModelLocator x:Key="Locator" />
</UserControl.Resources>
<UserControl.DataContext>
<Binding Source="{StaticResource Locator}" Path="Main" />
</UserControl.DataContext>
<UserControl.ContextMenu>
<ContextMenu x:Name="CtContextMenu"
DataContext="{Binding Path=PlacementTarget, RelativeSource={RelativeSource Self}}">
<MenuItem Header="Print Current View"
Command="{Binding Path=DataContext.PrintCurrentViewCmd}"
CommandParameter="{Binding Path=Template.MyViewBox.Child}"/>
</ContextMenu>
</UserControl.ContextMenu>
<UserControl.Style>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type UserControl}" >
<Viewbox x:Name="MyViewBox">
<ContentControl Name="MyContentControl" Content="{TemplateBinding Content}" />
</Viewbox>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</UserControl.Style>
【问题讨论】:
标签: c# wpf xaml mvvm data-binding