Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listbox selection does not go up or down the list when arrow button pressed

Tags:

wpf

xaml

Why Listbox jumps from last record to first when I press up or down arrow key once?

Here is 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 Behind

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 managed to reproduce it in isolation in the above code, so when the window appears Listbox will have last item selected, if I press up arrow key it jumps to the first item no to a previous one. I tried Mode TwoWay, UpdateSourceTriggerPropertyChange etc on this couple of lines of XAML, but nothing worked.

It only happens at the begining once it jumps to the top it then behaves as it should, if I grab a mouse and click on the item and then use keyboard it also works.

like image 416
adminSoftDK Avatar asked Oct 30 '22 11:10

adminSoftDK


1 Answers

This happens because when you set focus to list box it dosent set focus to selected item, use this code to set focus to 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>
like image 101
Muds Avatar answered Jan 04 '23 15:01

Muds