Ievgen
Ievgen

Reputation: 4443

WPF ListBox sometimes ignoring SelectedItem change

I have list box with next properties:

SelectedItem="{Binding SelectedItem, Mode=TwoWay}"
x:Name="listBox"
ItemsSource="{Binding Items}"

In code i have one static model and it can be used in few windows.

Only one window can be displayed at the same time.

Everything is working without any problems if UI already loaded. But when window is just ready to be loaded i set SelectedItem does nothing (first item is selected)

When i set brakepoint i noticed SelectedItem called from view with NULL or first item. (StackTrace doesnot contains my code)

I tryed to set selected item before view loaded and after:

model.SelectedItem=first;

view.Loaded += (o, e) => 
{
    model.SelectedItem=first; 
}

And still i have same problem.

Upvotes: 0

Views: 930

Answers (2)

Ievgen
Ievgen

Reputation: 4443

Сhanging order of properties solved the problem. Bind ItemsSourcefirst and then SelectedItem.

Upvotes: 0

Luke Marlin
Luke Marlin

Reputation: 1398

I think that Xaml DataBinding is evaluated during the loading of the window. So it is normal that SelectedItem is null within SelectionChanged event if it's fired before Window.Loaded occurred.

You can verify this by checking if your listbox has items before the window is fully loaded.

Upvotes: 1

Related Questions