如何在WPF中同步ListBox SelectedItem和焦点项目? [英] How to Synchronize ListBox SelectedItem and the focused item in WPF?

查看:260
本文介绍了如何在WPF中同步ListBox SelectedItem和焦点项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将按钮创建为ListBox项.使用键盘快捷键,所选项目/按钮将更改为第一个字符与按下的键相同的按钮.问题是焦点项目(虚线矩形)将不会与所选项目同步.如果使用键盘箭头,则不存在此问题.缩短的代码是:

I create buttons as ListBox items. Using keyboard shortcut, the selected item/button will be changed to the button where the first character is the same with the pressed key. The problem is the focused item (dashed rectangle) will not be synchronized with selected item. This problem doesn't exist if we use keyboard arrow. The shorted code is:

        <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>

中您如何以编程方式将焦点设置到已经具有焦点的WPF列表框中的SelectedItem?,解决方案是使用Focus方法并在C#端.

In How do you programmatically set focus to the SelectedItem in a WPF ListBox that already has focus?, the solution is using the Focus method and in C# side.

是否可以在MVVM中仅使用XAML?

推荐答案

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

I found the answer from my colleague. By Triggering FocusManager.FocusedElement with current selected item setter (IsSelected property) the problem is solved.

        <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>

这篇关于如何在WPF中同步ListBox SelectedItem和焦点项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆