【发布时间】:2014-10-04 00:41:02
【问题描述】:
我将按钮创建为 ListBox 项。使用键盘快捷键,所选项目/按钮将更改为第一个字符与按下的键相同的按钮。问题是焦点项目(虚线矩形)不会与选定项目同步。如果我们使用键盘箭头,则不存在此问题。短代码为:
<ListBox x:Name="ListBoxRef"
ScrollViewer.HorizontalScrollBarVisibility="Disabled"
DataContext="{Binding Path=ListViewSource}" IsSynchronizedWithCurrentItem="True"
ItemsSource="{Binding}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button Tag="{Binding}" IsTabStop="False"
Command="{Binding ElementName=UserControlTypeSelectionView, Path=DataContext.SelectCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource Self}}">
<Button.Template>
<ControlTemplate>
<TextBlock Text="{Binding Path=Name}" />
</ControlTemplate>
</Button.Template>
</Button>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ListBox>
在How do you programmatically set focus to the SelectedItem in a WPF ListBox that already has focus? 中,解决方案是使用Focus 方法并在C# 端。
是否可以在 MVVM 中仅使用 XAML?
【问题讨论】:
-
您也许可以使用附加的行为来同步它们。作为纯 xaml 的解决方法,您可以隐藏虚线焦点矩形,从而消除问题。
-
@pushpraj 是的,这是我目前的解决方案。但我不确定这是最好的解决方案。如果可能的话,我希望只在 XAML 中解决而不添加扩展。
-
尝试将空或空的焦点模板添加到列表框项。