按箭头按钮时,列表框选择不会在列表中上下移动

adm*_*tDK 5 wpf xaml

当我向上或向下按箭头键一次时,为什么列表框从最后一条记录跳到第一条?

以下是如何重现此问题

主窗口

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ListBox x:Name="MyListbox"
         ItemsSource="{Binding Entities}"
         SelectedItem="{Binding SelectedEntity}" />
</Window> 
Run Code Online (Sandbox Code Playgroud)

代码背后

public partial class MainWindow
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new MainWindowViewModel();
        MyListbox.Focus();
    }
}
Run Code Online (Sandbox Code Playgroud)

视图模型

public class MainWindowViewModel : NotifyPropertyChanged
{
    public MainWindowViewModel()
    {
        Entities = new ObservableCollection<string>()
        {
            "Batman",
            "Superman",
            "Shrek",
            "Jack Frost",
            "Wolverine"
        };
        SelectedEntity = Entities.Last();
    }

    public ObservableCollection<string> Entities { get; set; }

    private string selectedEntity;
    public string SelectedEntity
    {
        get { return selectedEntity; }
        set { OnPropertyChanged(ref selectedEntity, value); }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在一个大型应用程序中发现了这个问题,并且我设法在上面的代码中单独重现它,所以当窗口出现时,Listbox将选择最后一个项目,如果我按向上箭头键,它会跳转到第一个项目no到之前的项目.我想Mode TwoWay,UpdateSourceTriggerPropertyChange等上这对夫妻XAML的行,但毫无效果.

它只发生在开始一旦它跳到顶部然后表现应该如此,如果我抓住一个鼠标并点击该项目然后使用键盘它也可以工作.

Mud*_*uds 3

发生这种情况是因为当您将焦点设置为列表框时,它没有将焦点设置为所选项目,也可以使用此代码将焦点设置为项目。

<ListBox.Resources>
        <Style TargetType="{x:Type ListBoxItem}">
            <Style.Triggers>
                <Trigger Property="IsSelected" Value="True">
                        <Setter Property="FocusManager.FocusedElement"
                                Value="{Binding RelativeSource={RelativeSource Self}}"></Setter>                    </Trigger>  
            </Style.Triggers>
        </Style>
</ListBox.Resources>
Run Code Online (Sandbox Code Playgroud)