如何同步ListBox SelectedItem和WPF中的焦点项?

时间:2014-08-11 08:36:22

标签: c# wpf xaml listbox

我创建了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?

2 个答案:

答案 0 :(得分:7)

我找到了同事的答案。通过使用当前选定的项目设置器(IsSelected属性)触发FocusManager.FocusedElement,问题得以解决。

        <ListBox.ItemContainerStyle>
            <Style TargetType="{x:Type ListBoxItem}">
                <!-- Edited: add pushpraj code to hide the dashed rectangle on focused item -->
                <Setter Property="FocusVisualStyle" Value="{x:Null}" /> 
                <Style.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter Property="FocusManager.FocusedElement" Value="{Binding RelativeSource={RelativeSource Self}}" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </ListBox.ItemContainerStyle>

答案 1 :(得分:1)

如果您对焦点(虚线)矩形不感兴趣并且只对纯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 ListBoxItem,它为FocusVisualStyle设置了一个空值,通常是虚线矩形。

这不等同于将焦点元素与所选项目同步,但它隐藏了焦点图层,因此不会出现虚线矩形。

相关问题