MVVM - ListBox SelectedItem Binding Property Going Null
- by Peanut
So i have a listbox:
<ListBox x:Name="listbox" HorizontalAlignment="Left" Margin="8,8,0,8" Width="272" BorderBrush="{x:Null}" Background="{x:Null}" Foreground="{x:Null}" ItemsSource="{Binding MenuItems}" ItemTemplate="{DynamicResource MenuItemsTemplate}" SelectionChanged="ListBox_SelectionChanged" SelectedItem="{Binding SelectedItem}">
</ListBox>
and i have this included in my viewmodel:
public ObservableCollection<MenuItem> MenuItems
{
get
{
return menuitems;
}
set
{
menuitems = value;
NotifyPropertyChanged("MenuItems");
}
}
public MenuItem SelectedItem
{
get
{
return selecteditem;
}
set
{
selecteditem = value;
NotifyPropertyChanged("SelectedItem");
}
}
and also in my viewmodel:
public void UpdateStyle()
{
ActiveHighlight = SelectedItem.HighlightColor;
ActiveShadow = SelectedItem.ShadowColor;
}
So, the objective is to call UpdateStyle() whenever selectedchanged event is fired. So in the .CS file, i call UpdateStyle().
The problem is, whenever I get into the selectionchanged event method, my ViewModel.SelectedItem is always null.
I tried debugging this to see if the binding was working correctly, and it is. When I click on an item in the listbox, the SelectedItem Set is triggered, setting the value... but somewhere inbetween that and the selected changed (In the CS File) It gets reset to Null.
Can anyone help out?
Thanks