adminSoftDK
adminSoftDK

Reputation: 2092

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

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.

Upvotes: 5

Views: 2536

Answers (2)

Luk&#225;š Koten
Luk&#225;š Koten

Reputation: 1253

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

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

It took me an hour to figure out...

Upvotes: 1

Muds
Muds

Reputation: 4116

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>

Upvotes: 4

Related Questions