[英]How to access UserControl's DataContext from another UserControl?
[英]How to reference an element in the UserControl's style from the UserControl's ContextMenu?
給定一個包含包含上下文菜單和控件模板的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>
上下文菜單是一個彈出窗口,它在其自己的可視樹中呈現,而不是作為其父級的子級呈現。 要實現您需要做的事情,您可以執行以下操作
<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"
Tag="{Binding Path=Child, RelativeSource={RelativeSource AncestorType={x:Type ViewBox}}}">
<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=PlacementTarget.Tag,Element=CtContextMenu}"/>
</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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.