How can I get the SelectedItem
of a ListBox
to be highlighted after setting the SelectedItem
in the ViewModel?
The ItemsSource
is bound to an ObservableCollection
of Bar
(the collection is a member of a class Foo
. A button is bound to a command that adds a new empty Bar
instance to the collection and then also sets SelectedItem
to the new empty instance.
After adding the instance to the collection, the ListBox
is updated to show the new blank Bar
. However, after setting the SelectedItem
property in the ViewModel, the new instance is not highlighted in the ListBox
but it is being set and the PropertyChanged
event is raised (the SelectedItem
is displayed elsewhere in the View).
Additional Details:
INotifyPropertyChanged
is implemented in a base ViewModel class, and also implemented in the Foo
and Bar
classes.
The ListBox
contains a custom ItemTemplate
to display Bar
members, and a custom ItemContainerStyle
that modifies the Background
for the IsMouseOver
trigger.
simplified xaml:
<ListBox ItemsSource="{Binding Path=MyFoo.BarCollection}"
SelectedItem="{Binding Path=SelectedItem,
UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"/>
<Button Content="Add New Bar"
Command="{Binding Path=AddBarCommand}"/>
simplified viewmodel:
private Foo _myFoo;
public Foo MyFoo
{
get { return _myFoo; }
set { _myFoo= value; OnPropertyChanged("MyFoo"); }
}
private Bar _selectedItem;
public Bar SelectedItem
{
get { return _selectedItem; }
set { _selectedItem = value; OnPropertyChanged("SelectedItem"); }
}
private void AddBar()
{
Bar newBar = new Bar();
MyFoo.BarCollection.Add(newBar);
SelectedItem = newBar ;
_unsavedChanges = true;
}