如何从样式设置器设置不同控件的属性

时间:2014-09-04 02:12:34

标签: wpf xaml binding

我有一个ListView,另一个ListView。每当我选择孩子ListView中的项目时,我希望在父ListView中选择其父项。例如:

<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>

我如何完成这项工作?更喜欢它在XAML中。

2 个答案:

答案 0 :(得分:2)

您只需设置下面的ListViewItem.ItemContainerStyle即可实现您的目标

<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>

答案 1 :(得分:0)

您可以简单地使用InnerControl类来实现此目的。

参考文献:

WPF Nested ListViews - selectedValue of parent ListView

否则你可以去RelativeSource

How to access controls parent's property in a style

希望它有所帮助!