c# - WPF中如何同步ListBox SelectedItem和焦点项?

标签 c# wpf xaml 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?

最佳答案

我从同事那里找到了答案。通过使用当前选定项 setter (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>

关于c# - WPF中如何同步ListBox SelectedItem和焦点项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25238991/

上一篇:c# mongodb 批量插入

下一篇:C#:不可变类

相关文章:

c# - 从 ASP.NET 中的 DropDownList 中选择后填充多个文本框

.net - 在 WPF 组合框中查找项目

c# - Xaml,按钮的click事件在命令之前运行?

c# - Azure Data Lake 中的 U-SQL 查询错误

c# - 如何从 MS Access 数据库中获取主键和外键详细信息

c# - WPF keyDown 响应时间准确性

silverlight - SL4。 ElementName 绑定(bind)在 DataTemplate 中不起作用

c# - Xaml 内部错误错误 WMC9999

c# - 此内存扫描器仅适用于字符串。我怎样才能找到号码?

c# - 如何更改 RichTextBox 的部分文本颜色