【问题标题】:Use trigger to change colour of a path declared in ResourceDictionary使用触发器更改在 ResourceDictionary 中声明的路径的颜色
【发布时间】:2012-09-08 05:23:42
【问题描述】:

我正在创建单选按钮样式。 RadioButton 有一个承载 ContentControl 的边框。 ContentControl 将其 Content 属性设置为在单独的 ResourceDictionary 中声明的 Path (FemaleVector)。当单选按钮 IsChecked 时,如何更改路径的 Fill 属性?以下是我到目前为止所拥有的。我可以更改边框的背景属性,但设置 ContentControl 的 Foreground 属性不会更改路径的颜色。 (没想到会这样。)

<Style x:Key="Female" TargetType="{x:Type RadioButton}">
    <Setter Property="Margin" Value="0,0,5,0"/>
    <Setter Property="Cursor" Value="Hand"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type RadioButton}">
                <Border x:Name="border" Padding="7,3,7,3" Width="35" Height="35" BorderBrush="#8CD567DC" Background="#00D567DC" CornerRadius="5" BorderThickness="0.8">
                    <ContentControl x:Name="content" Content="{DynamicResource FemaleVector}"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="Background" TargetName="border" Value="#8CD567DC"/>
                        <Setter Property="Foreground" TargetName="content" Value="Blue"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

我不喜欢在我的样式中包含路径的长 Data 属性,因此我将它们移到了单独的 ResourceDictionary 中。我应该将路径放回我的样式中,而不是将其保存在单独的 ResourceDictionary 中吗?

编辑:类似的问题是herehere

【问题讨论】:

    标签: wpf triggers


    【解决方案1】:

    如果样式没有在某处重复使用,我个人会将其保存在本地样式资源部分。这样你就能看到更大的画面。否则,最好将其保存在 ResourceDictionary 中:)

    无论哪种方式,您都应该能够更改 Fill 属性:

    <Setter Property="Content.Fill" TargetName="content" Value="Blue"/>
    

    如果这不起作用,我建议更多方法: 您可以在 Xaml 中使用 Trigger.EnterActions。或许通过动画设置属性效果会更好?带有 setter 的 ControlTemplate 触发器有时会受到限制。

    还有相对绑定。但你必须小心。 (如果你想让它可重复使用) 在您的 FemaleVector 样式中,您可以将 Fill 与 ContentControl Foreground 绑定。在 Google 中查找 RelativeBinding。

    然后是属性继承。如果在 FemaleVector 中设置填充颜色,则需要使用样式。如:

    <Style>
    <Setter Property="Fill" Value="BLACK" />
    </Style>
    

    您可以稍后设置 ContentControls 样式并在那里添加触发器,例如:

    <ContentControl.Style>
    <Style>
    <Style.Triggers>
    <DataTrigger Binding={Binding IsChecked, RelativeSource={RelativeSource AncestorType=RadioButto}} Value=TRUE>
    <Setter Property="Path.Fill" Value="BLACK" />
    </DataTrigger>
    

    【讨论】:

    • 您好,感谢您的宝贵时间。我尝试了您的建议,但无法编译:抱怨“找不到类型'内容'”。此外,该路径可能会在其他地方使用。
    • 添加了更多选项。我知道其中至少有一个必须工作。祝你好运:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-16
    • 1970-01-01
    • 2021-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多