【问题标题】:XAML trigger template to set visibilty based on another elementXAML 触发器模板基于另一个元素设置可见性
【发布时间】:2011-10-24 09:49:13
【问题描述】:

我有几个 StackPanel 可以根据 ToggleButtons 更改可见性。如果我在DataTrigger 行上将Tag 替换为btn1,则下面的代码有效。 如何使用Tag 属性的值?

<Window x:Class="MyTestApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="TestApp">

    <Window.Resources>
        <Style x:Key="panelStyle" TargetType="{x:Type StackPanel}">
            <Style.Triggers>
                <DataTrigger Binding="{Binding ElementName=Tag, Path=IsChecked}" Value="False">
                    <Setter Property="StackPanel.Visibility" Value="Collapsed" />
                </DataTrigger>
                <DataTrigger Binding="{Binding ElementName=Tag, Path=IsChecked}" Value="True">
                    <Setter Property="StackPanel.Visibility" Value="Visible" />
                </DataTrigger>
            </Style.Triggers>
        </Style>

    </Window.Resources>

    <WrapPanel>
        <ToggleButton Content="One" Name="btn1" />
        <ToggleButton Content="Two" Name="btn2" />

        <StackPanel Style="{StaticResource panelStyle}" Tag="{Binding btn1}">
            <Label Content="Data to panel 1" />
        </StackPanel>

        <StackPanel Style="{StaticResource panelStyle}" Tag="{Binding btn2}">
            <Label Content="Data to panel 2" />
        </StackPanel>

    </WrapPanel>

</Window>    

这个问题非常相似,但我缺少有关如何传递元素名称的详细信息。
XAML - Generic textbox stylewith triggers / parameters?

【问题讨论】:

    标签: wpf xaml triggers


    【解决方案1】:

    您的绑定不正确。

    在您的DataTemplate 中,绑定应该是:

    <DataTrigger Binding="{Binding Path=Tag.IsChecked, RelativeSource={RelativeSource Self}}" Value="False">
       <Setter Property="StackPanel.Visibility" Value="Collapsed" />
    </DataTrigger>
    

    这里RelativeSource 模式为Self 告诉绑定引擎要绑定的对象是应用样式的对象(例如您的StackPanel)。 PropertyPathTag.IsChecked 告诉绑定引擎从存储在 Tag 中的对象中查找名为 IsChecked 的属性。

    最后,StackPanel 中的绑定应该是:

    <StackPanel Style="{StaticResource panelStyle}" Tag="{Binding ElementName=btn1}">
       <Label Content="Data to panel 1" />
    </StackPanel>
    

    这里ElementName 创建到逻辑树中另一个元素的绑定。如果您没有像原始示例中那样明确分配 Binding 中的任何属性:

    Tag="{Binding btn1}"
    

    指定的值分配给Path 属性。所以这将与以下内容相同:

    Tag="{Binding Path=btn1}"
    

    另外请注意,使用Tag 不被认为是最佳实践,因为它的类型是object,并且它的使用不受限制,因此可以在整个项目中具有任意数量的不同含义(这通常使得难以理解,尤其是在远离实际使用的Templates中使用时)。

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      使用转换器:设置 StackPanel 的可见性:

      <StackPanel Visivility="{Binding IsChecked, ElementName=btn1, Converter={StaticResource BooleanToVisibilityConverter}}">
        ...
      </StackPanel>
      

      【讨论】:

        猜你喜欢
        • 2016-12-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-23
        • 1970-01-01
        • 2021-04-12
        • 2011-10-23
        • 2022-12-14
        相关资源
        最近更新 更多