我创建按钮作为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?中,解决方案是使用焦点方法和C#端。
是否可以仅在MVVM中使用XAML?
发布于 2014-08-11 08:59:27
如果您对焦点(虚线)矩形不感兴趣,而只对纯xaml解决方案感兴趣,那么您可能会隐藏它。
这是一个样本
<ListBox>
<ListBox.Resources>
<Style TargetType="ListBoxItem">
<Setter Property="FocusVisualStyle"
Value="{x:Null}" />
</Style>
</ListBox.Resources>
<ListBoxItem>item 1</ListBoxItem>
<ListBoxItem>item 2</ListBoxItem>
<ListBoxItem>item 3</ListBoxItem>
</ListBox>
示例中有趣的区域是Style
for ListBoxItem
,它为FocusVisualStyle
设置一个空值,该值通常是虚线矩形。
这并不等同于将聚焦元素与所选项同步,但它隐藏焦点层,因此不会出现虚线矩形。
https://stackoverflow.com/questions/25238991
复制相似问题