【发布时间】:2011-06-11 23:25:46
【问题描述】:
<DataTemplate x:Key="_ItemTemplateA">
<Grid Tag="{Binding Path=DataContext.Command, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type UserControl}}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<ContentControl Content="{Binding}" ContentTemplate="{StaticResource ContentTemplateB}" Grid.Row="0" />
<ContentControl Name="uiContentPresenter" Content="{Binding ContentView}" Grid.Row="1" Height="0" />
<ContentControl DataContext="{Binding IsContentDisplayed}" DataContextChanged="IsDisplayed_Changed" Visibility="Collapsed" />
<Grid.ContextMenu>
<ContextMenu>
<MenuItem Header="Text"
Command="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"
CommandParameter="{Binding}" />
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</DataTemplate>
上面的数据模板被应用到一个ItemsControl。问题是,对于为 Grid 指定的 ContextMenu,PlacementTarget 属性实际上从未设置为任何内容,因此我无法访问 Grid 的 Tag 属性,这是传递应该在父 UserControl 上执行的命令所必需的到上下文菜单。我已经基于类似的例子建立了这种方法,例如:http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/0244fbb0-fd5f-4a03-bd7b-978d7cbe1be3/
我无法确定任何其他传递此命令的好方法。这是这样设置的,因为我们使用的是 MVVM 方法,因此我们必须执行的命令存在于应用此模板的用户控件的视图模型中。我尝试以几种不同的方式显式设置 PlacementTarget 但它仍然总是显示为未设置。
【问题讨论】:
-
我也面临同样的问题...任何解决方法。
-
我也遇到了这个问题。对我来说,它是
ListView。我在UserControl的Loaded事件处理程序中放置了一个断点,并检查了<ListView.ContextMenu>的PlacementTarget属性...null。 :( -
当我的 ContextMenu 打开时,我也面临 PlacementTarget 为空的问题,导致无法链接回窗口/用户控件中的信息。
标签: wpf xaml wpf-controls binding