wpf - 如何跟踪 ItemsControl 的哪个元素导致 ContexMenu 打开?
问题描述
在我的图书编辑器应用程序中,我需要按层次顺序显示主题和子主题,所以我做了这样一个标记:
<StackPanel>
<ScrollViewer>
<Grid ColumnDefinitions="auto, *" RowDefinitions="auto">
<ItemsControl Grid.Column="0" Grid.Row="0" Items="{Binding Book.Themes}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<Button Content="{Binding Name}" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataContext.UpdateSubthemesVisibilityCommand}" CommandParameter="{Binding Name}"/>
<ItemsControl Items="{Binding Subthemes}" IsVisible="{Binding AreSubthemesVisible}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Content="{Binding Name}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ContextMenu>
<ContextMenu>
<MenuItem Header="Rename" />
<MenuItem Header="Delete"/>
</ContextMenu>
</ItemsControl.ContextMenu>
</ItemsControl>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
<ItemsControl.ContextMenu>
<ContextMenu>
<MenuItem Header="Rename" Command="{Binding RenameThemeCommand}" CommandParameter="...How to bind it to button which cause menu to open"/>
<MenuItem Header="Delete"/>
</ContextMenu>
</ItemsControl.ContextMenu>
</ItemsControl>
</Grid>
</ScrollViewer>
</StackPanel>
也许标记不是很清楚,但关键是我有外部 ItemsControl 和内部的。外部项目具有结构:按钮(主题名称)+ 内部 ItemsControl,它也将子主题的名称显示为按钮。这是屏幕截图:
每个 ItemsControl 都有自己的 ContextMenu,但我无法正确绑定它们。我希望“重命名”MenuItems 绑定到 Button.Content 的 Button 右键单击导致菜单打开。我应该怎么做?
我正在使用 MVVM Avalonia,但我希望在 WPF 中它的工作方式相同,以便我可以将 WPF 主题标签添加到这个问题中。
解决方案
您不需要将 ContextMenu 添加到 ItemsControl。它需要被添加到 ItemsControl 中。
这是在 ItemContainerStyle 中完成的。
在这种情况下,在 ContextMenu DataContext 中将包含调用 ContextMenu 的元素。
例子:
<Window.Resources>
<spec:StringCollection x:Key="strings">
<sys:String>First</sys:String>
<sys:String>Second</sys:String>
<sys:String>Third</sys:String>
</spec:StringCollection>
<Style x:Key="ItemStyle" TargetType="ContentPresenter">
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu>
<TextBlock Text="{Binding}"/>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<ItemsControl ItemsSource="{StaticResource strings}"
ItemContainerStyle="{StaticResource ItemStyle}"/>
推荐阅读
- sql - SQL 语句是否可以将其与添加的Suggested_phrase 列分组,基于接近或匹配同一列表中的每个单词
- vb.net - Datagridview 行显示模糊数据
- javascript - 如何使用 XMLHttpRequest 解决或屏蔽 Chrome 扩展的“SameSite”cookie 错误
- time-series - 为什么某些时间序列模型(ARIMA、BATS、ETS)会为预测生成平线?
- embedded - 扩展 u-boot 功能
- java - 如何使用底部导航视图处理 MainActivity 上另一个片段的侦听器?
- google-cloud-storage - terraform中的base64编码的md5哈希?
- github - 配置 Travis CI 以构建新的 github 分支
- ios - 使用 Swift 解析嵌套 JSON 数据的正确方法是什么?
- python - 使用 pdb 调试 tox python 测试?