0
votes

Using an MVVM approach, I have a View that contains a ListBox and also a Grid in which I want to display information about the SelectedItem in the ListBox. I want to set the DataContext for the Grid to the SelectedItem.

However, the ListBox is buried as follows: A ContentControl that is bound to a DataTemplate that is a UserControl View that contains the ListBox.

Here is the MainWindow Grid that I'm not sure how to bind:

<Grid DataContext="{Binding ElementName=MyList, ????}">

Here is the ContentControl in the same View:

<ContentControl x:Name="MyList"
                Content="{Binding}" 
                ContentTemplate="{StaticResource MyListTemplate}"/>

Here is the Data Template in the same View:

    <Window.Resources>
        <DataTemplate x:Key="MyListTemplate">
            <v:MyListView/>
        </DataTemplate>
    </Window.Resources>

Here is MyListView:

<UserControl>
    <ListBox Name="MyListBox" ItemsSource="{Binding ItemList}"/>
</UserControl>

I am adding to code I wrote a couple of years ago and have been away from WPF for a while, so alas, I am rusty on my data binding. I have been trying to add a SelectedItem property to the view model for MyListView and/or the MainWindow. I expect this may require RelativeSource.

1

1 Answers

0
votes

Doh! I was forgetting to specify the OnPropertyChanged call for my property.

In the UserControl ListBox, I needed this:

ItemsSource="{Binding ItemList}" SelectedItem="{Binding MySelectedItem}"

In the main window view model, I needed this:

public MyItemViewModel MySelectedItem
{
    get { return _mySelectedItem; }
    set
    {
        _mySelectedItem = value;
        OnPropertyChanged("MySelectedItem");
    }
}

Then, in the main window, the binding is simply:

<Grid DataContext="{Binding MySelectedItem}">