WPF将自定义ContextMenu添加到另一个视图中引用的视图中



我试图完成的是将上下文菜单放置到另一个视图中引用的列表框项目中,例如:

<UserControl x:Class="Foo.Bar.MyTestApp.Views.ListBoxPresenterView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:views="clr-namespace:Foo.Bar.MyTestApp.Views">
<Grid>

<views:MyListBoxView />
</Grid>
</UserControl>

这显示我的MyListBoxView.xaml很好。然而,我想知道的是,是否可以向视图添加上下文菜单:ListBoxPresenterView.xaml中的MyListBoxView。原因是我只想让MyListBoxView.xamm尽可能通用。所以,如果我想对它做任何特殊的修改,那么就让它只在引用它的类中

所以本质上它会像:

<views:MyListBoxView >
<style TargetType="ListBoxItem">
... add context menu to a list box item template
</ListBox>
<views:MyListBoxView />

如有任何想法,我们将不胜感激。

如果MyListBoxView确实是ListView,您可以像往常一样设置其或其项目容器的ContextMenu

<views:MyListBoxView>
<views:MyListBoxView.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu />
</Setter.Value>
</Setter>
</Style>
</views:MyListBoxView.ItemContainerStyle>
</views:MyListBoxView>

如果它是UserControl,则可以将依赖属性添加到UserControl,然后在MyListBoxView的XAML标记中添加。

列表框演示者视图:

<views:MyListBoxView ItemContextMenu="..." />

MyListBoxView:

<Setter Property="ContextMenu"
Value="{Binding ItemContextMenu, RelativeSource={RelativeSource AncestorType=UserControl}}">

最新更新