views:

366

answers:

2

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

Edit: I thought I might shed a little more light. 1. Click on an item in the list 2. SelectedItem.Set gets triggered, ViewModel.SeletedItem gets set correctly. 3. Enter the OnSelectionChanged Event in the .CS file. 4. Enter ViewModel.UpdateStyle() 5. SelectedItem Throws a Null Exception.

A: 

Look to see if your backing property (selecteditem) is getting set to NULL somewhere in your code.

Zamboni
Nope - The only place SelectedItem is being used is in UpdateStyle and the Binding.
Peanut
I mean the lower case selecteditem, where does that get set, it is not the same as SelectedItem.
Zamboni
+1  A: 

Wow, found a strange issue:

<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource MainViewModelDataSource}}" d:DataContext="{d:DesignData /SampleData/MainViewModelSampleData.xaml}">

That code is generated by Expression Blend - and it was causing the issue. I erased all generated binding and just made a this.datacontext a new VM in the constructor of the XAML... now its working.

Thanks anyway, guys.

Peanut