views:

199

answers:

2

I don't know if this is the right way to phrase the question or not. Here is a typically databinding example:

<UserControl x:Name="root">
   <ListView ItemsSource="{Binding MyItemsSource, ElementName=root}" />
</UserControl>

But this is what I want to be able to do:

<UserControl DataContext="{Binding SelectedItem, ElementName=lstMyItems}">
   <ListView ItemsSource="{Binding MyItemsSource, ElementName=root}">
</UserControl>

(Notice that what I'm doing here is setting the DataContext of the UserControl to the currently SelectedItem on the ListView).

Any clean way of doing this without events or using code-behind?

A: 

As long as you're not doing it at the UserControl level, you almost answered your own question. For example:

<UserControl DataContext="{Binding SelectedItem, ElementName=lstMyItems}">
   <Grid x:Name="_grid">
       <ListView ItemsSource="{Binding MyItemsSource, ElementName=_grid}">
   </Grid>
</UserControl>

The reason it doesn't work at the root level isn't entirely clear to me, but I think it has something to do with name scoping.

HTH, Kent

Kent Boogaart
+1  A: 

I solved my problem by doing this:

<UserControl x:Name="root">   
    <ListView ItemsSource="{Binding MyItemsSource}" 
        SelectedItem="{Binding DataContext, ElementName=root, Mode=OneWayToSource}">
</UserControl>

The trick is in the Mode=OneWayToSource setting.

Micah