0

I have a ListView and inside this another ListView. Whenever I select an item in a child ListView I want the parent of that to be selected in the parent ListView. Example:

<Window>
    <Window.Resources>
        <!-- Parent ListView ItemsTemplate... Incomplete -->
        <DataTemplate x:Key="parentItemTemplate">
            <!-- Child ListView -->
            <ListView SelectedItem="{Binding ChildSelectedItem}" ItemsSource="{Binding WhateverInParent}">
                <ListView.Resources>
                    <Style TargetType="ListViewItem">
                        <Trigger Property="IsSelected" Value="True">
                            <!-- This is what I want to do, but ofc this doesn't work because it produces a compile error saying can't set TargetName in a setter -->
                            <Setter TargetName="parent" Property="SelectedValue" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=ListView}}" />
                        </Trigger>
                    </Style>
                </ListView.Resources>
            </ListView>
        </DataTemplate>
    </Window.Resources>
    <ListView ItemsTemplate="{StaticResource parentItemTemplate}" x:Name="parent" SelectedItem="{Binding ParentSelectedItem}" ItemsSource="{Binding Whatever}"/>
</Window>

How do I get this done? Would prefer it to be in XAML.

nakiya
  • 14,063
  • 21
  • 79
  • 118

2 Answers2

2

You just need to set the ListViewItem.ItemContainerStyle like below to achieve what you want

<ListView ItemsTemplate="{StaticResource parentItemTemplate}" x:Name="parent" SelectedItem="{Binding ParentSelectedItem}" ItemsSource="{Binding Whatever}">
   <ListView.ItemContainerStyle>
      <Style TargetType="ListViewItem">
         <Style.Triggers>
             <Trigger Property="IsKeyboardFocusWithin" Value="true">
               <Setter Property="IsSelected" Value="true" />
             </Trigger>
         </Style.Triggers>
      </Style>
    </ListView.ItemContainerStyle>
</ListView>
Nitin
  • 18,344
  • 2
  • 36
  • 53
  • +1, Looks good. The only problem is when I click outside the parent ListView, the current selection gets deselected. – nakiya Sep 04 '14 at 04:24
0

You could simply use the InnerControl class to achieve this.

References:

WPF Nested ListViews - selectedValue of parent ListView

Or else you can go for RelativeSource:

How to access controls parent's property in a style

Hope it helps!

Community
  • 1
  • 1
Kulasangar
  • 9,046
  • 5
  • 51
  • 82