我花了很长时间寻找一个简单直接的答案,但到目前为止失败了。我找到了对我有帮助的混合答案,但所有这些答案都会为非常非常简单的事情生成大量代码:
如何通过在 WPF TreeView 中单击来获取所选项目?
我已经知道如何获取所选项目或如何通过右键单击选择项目或如何通过按键延迟项目选择(所有答案都在这里找到),但我只想知道用户何时单击元素。这是必需的,因为我有一个 TreeView ,用户可以使用箭头键导航(这将更改 IsSelected),但我只需在单击该项目或按下 Return 键时执行一些逻辑。
我想要一个纯粹的 MVVM 解决方案。如果那不可能,我在这里非常绝望,所以任何不可怕的事情都会有所帮助。
最佳答案
例如,如果您将 MouseDown
视为您的点击,您可以执行以下操作:
xaml:
<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());
}
这样,只有在 ListBoxItem
上按下鼠标或按下 Enter 键时,才会调用 MessageBox
。当箭头键改变选择时不会。 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;
}
}
xaml:
<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
将具有“选中”/“输入键命中”的列表框的索引
关于wpf - 如何在WPF中仅通过单击来获取选定的TreeViewItem?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16398543/