sll*_*sll 3 .net c# wpf listview
我有一个ListBoxItem的数据模板,它包含几个按钮,以及很少的自定义控件,如网格或图表.每个按钮都绑定到一个合适的命令处理程序,ListView控件的SelectedIndex属性也绑定到ViewModel的属性.
问题:在命令处理程序(绑定到按钮)中我无法解析当前选定的项目/索引,因为它在单击ListBox项目中的按钮或其他控件时没有改变,但是当我单击ListBoxItem区域本身时 - SelectedIndex正在改变.
问题是如何在单击ListBoxItem中的任何控件时触发SelectedIndex被更改?
将此添加到您的 ListBox.Resources
<ListBox.Resources>
<Style TargetType="{x:Type ListBoxItem}">
<Style.Triggers>
<Trigger Property="IsKeyboardFocusWithin" Value="True">
<Setter Property="IsSelected" Value="True" />
</Trigger>
</Style.Triggers>
</Style>
</ListBox.Resources>
Run Code Online (Sandbox Code Playgroud)
编辑
只要具有键盘焦点,上一个方法仅选择ListBoxItem.如果将焦点移出ListBoxItem,它将再次被取消选中.
这是键盘焦点在项目中移动时选择ListBox项目的另一种简单方法,当焦点移出ListBoxItem时它保持选中状态
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>
Run Code Online (Sandbox Code Playgroud)
而在守则背后
protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
ListBoxItem item = (ListBoxItem)sender;
item.IsSelected = true;
}
Run Code Online (Sandbox Code Playgroud)