c# - 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 />
对此的任何想法将不胜感激。
解决方案
如果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}}">
推荐阅读
- python - 滑动窗口算法 - start < n 的条件
- excel - 如何让 Excel 中 ActiveX InputBox 的输入出现在我的 VBA 代码中?
- python - 使用 Python (WIN32com) 在 Excel 中创建数据透视表切片器
- c# - 无法从空对象调用方法或检索属性。以下调用堆栈返回的对象为空
- airflow - Cloud Composer/Airflow Task Runner Storage
- swift - 如何在 swiftui 中显示来自网络的图像?
- erlang - Erlang - 主管不会重新启动工作进程
- python - 如何在 RandomForestClassifier 中选择 n_estimators?
- java - sudo ln -sfn 有什么作用?
- gremlin - Gremlin 查询不起作用 - 如果不存在,则为 2 x 顶点并添加边