我有一個帶有不同類的項目的ListBox。 DataTemplates用於以適當的方式呈現這些對象。我想在這些類的DataTemplates中有不同的上下文菜單。帶有DataTemplate的ListBox Item上的ContextMenu
一切工作正常使用鼠標,但使用鍵盤我無法調出上下文菜單。
這可能是因爲鍵盤焦點不在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
{
}
}
的列表框上下文菜單中的列表框的中間打開,不選定的項目在哪裏。另外,我想在XAML中聲明上下文菜單項,這使得全球化比將其放入代碼更容易。鍵盤焦點對視力受損用戶至關重要,或因其他原因避免使用鼠標的用戶。 – Guge 2010-09-23 11:33:30