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.
source share