【问题标题】:How to set a property of a different control from a style setter如何设置与样式设置器不同的控件的属性
【发布时间】:2014-10-28 15:54:05
【问题描述】:

我有一个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 中。

【问题讨论】:

  • 不能通过 style..但是你为什么要这样做?并且 ListView 没有 IsSelected 属性。你想达到什么目标?
  • @nit:因为这是用户要求。已编辑。

标签: wpf xaml binding


【解决方案1】:

您可以简单地使用InnerControl 类来实现这一点。

参考资料:

WPF Nested ListViews - selectedValue of parent ListView

或者你可以去RelativeSource:

How to access controls parent's property in a style

希望对你有帮助!

【讨论】:

    【解决方案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,看起来不错。唯一的问题是当我在父 ListView 之外单击时,当前选择被取消选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-03
    • 2012-02-18
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-05
    相关资源
    最近更新 更多