我有一个 ListBoxItem 的数据模板,其中包含几个按钮,以及一些自定义控件,如 Grid 或 Chart。每个按钮都绑定(bind)到适当的命令处理程序,ListView 控件的 SelectedIndex 属性也绑定(bind)到 ViewModel 的属性。
问题:在命令处理程序(绑定(bind)到按钮)中,我无法解析当前选定的项目/索引,因为在单击列表框中的按钮或其他控件时它没有改变项,但是当我单击 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>
编辑
只要 ListBoxItem 具有键盘焦点,之前的方法只会使它处于选中状态。如果您将焦点移出 ListBoxItem,它将再次变为未选中状态。
这是另一种简单的方法,当键盘焦点在项目内移动时选择 ListBox 项目,并且当焦点移出 ListBoxItem 时它保持选中状态
<Style TargetType="{x:Type ListBoxItem}">
<EventSetter Event="PreviewGotKeyboardFocus" Handler="SelectCurrentItem"/>
</Style>
在代码背后
protected void SelectCurrentItem(object sender, KeyboardFocusChangedEventArgs e)
{
ListBoxItem item = (ListBoxItem)sender;
item.IsSelected = true;
}
关于c# - 单击 ListBoxItem 区域内的任何控件时触发器 SelectedIndex 发生更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6680987/