How can I bind a property to an element at the bottom in the visual tree?

I don't know if this is the right way to formulate the question or not. Here's a typical example of data binding:

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

      

But this is what I want to do:

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

      

(Note that what I'm doing here is setting the DataContext UserControl for the current SelectedItem in the ListView).

Any clean way to do this without events or with code?

0


source to share


2 answers


I solved my problem by following these steps:

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

      



The trick is setting Mode = OneWayToSource.

+1


source


Until you do it on a level UserControl

, you almost answered your 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 is not entirely clear to me, but I think it has to do with the scope of the naming convention.

0


source







All Articles