首页 > 解决方案 > 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.xaml 尽可能通用。所以如果我想对它做任何特殊的修改,那就让它只在引用它的类中。

所以基本上它会是这样的:

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

对此的任何想法将不胜感激。

标签: c#wpfxaml

解决方案


如果MyListBoxView确实是 a ,您可以像往常一样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,您可以在 的 XAML 标记中添加一个依赖属性UserControl,然后添加到它MyListBoxView

列表框演示者视图:

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

我的列表框视图:

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

推荐阅读