List selection does not increase or decrease in the list when you press the arrow button

Why does the Listbox jump from the last entry to the first when I press the up or down arrow key once?

Here's how to reproduce this problem

Mainwindow

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

Code for

 public partial class MainWindow { public MainWindow() { InitializeComponent(); DataContext = new MainWindowViewModel(); MyListbox.Focus(); } } 

ViewModel

 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); } } } 

I found this problem in a large application, and I was able to reproduce it in isolation in the above code, so when the window appears, the last item will be selected in Listbox, if I press the arrow key, it goes to the first item no to the previous one. I tried Mode TwoWay , UpdateSourceTriggerPropertyChange etc. On this pair of XAML lines, but nothing worked.

This happens only at the beginning, as soon as it jumps up, it behaves as it should, if I take the mouse and click on an element and then use the keyboard, it also works.

+5
source share
2 answers

This is because when you set focus on the list box, its dosage sets focus on the selected item, use this code to set focus on the item as well.

 <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> 
+2
source

I realized that setting IsTabStop = "False" in the ListBoxItem causes the same behavior that you reported.

 <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="IsTabStop" Value="False"/> </Style> </ListBox.ItemContainerStyle> 

It took me an hour to understand ...

0
source

Source: https://habr.com/ru/post/1240934/


All Articles