我有一个包含不同类别项目的列表框。数据模板用于以适当的方式呈现这些对象。我希望在这些类的 DataTemplates 中有不同的上下文菜单。
使用鼠标一切正常,但使用键盘我无法调出上下文菜单。
这可能是因为键盘焦点不在 DataTemplate 的内容上,而是在 ListBoxItem 上。
如何让 ListBoxItem 引用内容的 ContextMenu?
示例代码:
<Window x:Class="WpfApplication8.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:my="clr-namespace:WpfApplication8"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<DataTemplate DataType="{x:Type my:Orange}">
<TextBlock>
Orange
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Peel"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
<DataTemplate DataType="{x:Type my:Apple}">
<TextBlock>
Apple
<TextBlock.ContextMenu>
<ContextMenu>
<MenuItem Header="Uncore"/>
</ContextMenu>
</TextBlock.ContextMenu>
</TextBlock>
</DataTemplate>
</Window.Resources>
<Grid>
<ListBox ItemsSource="{Binding Fruits}"/>
</Grid>
</Window>
using System.Windows;
using System.Collections.ObjectModel;
namespace WpfApplication8
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Fruits = new ObservableCollection<Fruit>();
Fruits.Add(new Apple());
Fruits.Add(new Apple());
Fruits.Add(new Orange());
this.DataContext = this;
}
public ObservableCollection<Fruit> Fruits { get; set; }
}
public class Fruit
{
}
public class Apple : Fruit
{
}
public class Orange : Fruit
{
}
}
最佳答案
我也遇到这个问题了。正在阅读Bea Stollnitz' blog给了我一个想法。
我开始在我的资源中使用这样的数据模板:
<ContextMenu x:Key="MyMenu">
<MenuItem Header="A" />
<MenuItem Header="B" />
<MenuItem Header="C" />
</ContextMenu>
<DataTemplate x:Key="MyTemplateKey" DataType="{x:Type local:myType}">
<TextBlock ContextMenu="{StaticResource MyMenu}" >
<Run Text="{Binding Path=MyBindingPath}" FontSize="20" FontWeight="Bold" />
</TextBlock>
</DataTemplate>
如上所述,这会导致键盘菜单键无法调用上下文菜单,尽管右键单击确实有效。问题是上下文菜单需要位于 ListBoxItem 上,而不是内部模板上。
嘿,快点!
<Style x:Key="ContextLBI" TargetType="{x:Type ListBoxItem}">
<Setter Property="ContextMenu" Value="{StaticResource MyMenu}">
</Setter>
</Style>
现在,只需从数据模板中删除 ContextMenu,然后在列表框中设置样式,如下所示:
<ListBox ItemTemplate="{StaticResource MyTemplateKey}"
ItemContainerStyle="{StaticResource ContextLBI}"
... >
</ListBox>
关于wpf - 具有 DataTemplate 的列表框项上的上下文菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3746248/