gpt4 book ai didi

wpf - XAML 触发器模板基于另一个元素设置可见性

转载 作者:行者123 更新时间:2023-12-01 12:59:02 25 4
gpt4 key购买 nike

我有几个基于 ToggleButtons 更改可见性的 StackPanel。如果我替换 Tag,则下面的代码有效与 btn1DataTrigger -行。
如何使用 Tag 的值属性(property)?

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

最佳答案

您的绑定(bind)不正确。

在您的 DataTemplate绑定(bind)应该是:

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

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

最后是 StackPanel 中的绑定(bind)应该:
<StackPanel Style="{StaticResource panelStyle}" Tag="{Binding ElementName=btn1}">
<Label Content="Data to panel 1" />
</StackPanel>

这里 ElementName创建到逻辑树中另一个元素的绑定(bind)。如果您没有明确分配给 Binding 中的任何属性就像你原来的例子一样:
Tag="{Binding btn1}"

指定的值分配给 Path属性(property)。所以这将与以下内容相同:
Tag="{Binding Path=btn1}"

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

希望这可以帮助!

关于wpf - XAML 触发器模板基于另一个元素设置可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7873797/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com