好吧,例如,如果您认为MouseDown
是您的点击,您可以执行以下操作:
xml:
<ListBox x:Name="testListBox">
<ListBoxItem Content="A" />
<ListBoxItem Content="B" />
<ListBoxItem Content="C" />
</ListBox>
代码隐藏:
testListBox.AddHandler(MouseDownEvent, new MouseButtonEventHandler((sender, args) => ItemClicked()), true);
testListBox.AddHandler(
KeyDownEvent,
new KeyEventHandler(
(sender, args) => {
if (args.Key == Key.Enter)
ItemClicked();
}),
true);
private void ItemClicked() {
MessageBox.Show(testListBox.SelectedIndex.ToString());
}
这样,只有在按下鼠标或按下 Enter 键MessageBox
时才会调用。ListBoxItem
当箭头键更改选择时不会。SelectedIndex
将保持所示的正确索引MessageBox
。
更新:
一种使用行为的 MVVM 方式:
public class ItemClickBehavior : Behavior<ListBox> {
public static readonly DependencyProperty ClickedIndexProperty =
DependencyProperty.Register(
"ClickedIndex",
typeof(int),
typeof(ItemClickBehavior),
new FrameworkPropertyMetadata(-1));
public int ClickedIndex {
get {
return (int)GetValue(ClickedIndexProperty);
}
set {
SetValue(ClickedIndexProperty, value);
}
}
protected override void OnAttached() {
AssociatedObject.AddHandler(
UIElement.MouseDownEvent, new MouseButtonEventHandler((sender, args) => ItemClicked()), true);
AssociatedObject.AddHandler(
UIElement.KeyDownEvent,
new KeyEventHandler(
(sender, args) => {
if (args.Key == Key.Enter)
ItemClicked();
}),
true);
}
private void ItemClicked() {
ClickedIndex = AssociatedObject.SelectedIndex;
}
}
xml:
<ListBox>
<i:Interaction.Behaviors>
<local:ItemClickBehavior ClickedIndex="{Binding VMClickedIndex, Mode=TwoWay}" />
</i:Interaction.Behaviors>
<ListBoxItem Content="A" />
<ListBoxItem Content="B" />
<ListBoxItem Content="C" />
</ListBox>
现在该属性VMClickedIndex
将具有“Cicked”/“Enter Key Hit”的 ListBox 的索引