基于父样式的样式触发器 属性

Style trigger based on parent style property

我想要有带有小图标的按钮作为内容。

图标定义并存储在 ResourceDictionary 中,如下所示:

<Path x:Key="BackIcon" Data="F1 M 57,42L 57,34L 32.25,34L 42.25,24L 31.75,24L 17... "/>
<Path x:Key="LoadFromFileIcon" Data="F1 M 48,39L 56,39L 56,49L 63.25,49L 52,60.2... "/>
<Path x:Key="SaveToFileIcon" Data="F1 M 48,60L 56,60L 56,50L 63.25,50L 52,38.75L... "/>

由于我还需要提供 Path.FillPath.Stretch 等属性,我决定制作自己的 IconButtonStyle 这样我就不必在每个Path 在图标字典中,像这样很容易地制作按钮:

<Button Style="{StaticResource IconButtonStyle}"
    Content="{StaticResource ResetIcon}"/>

这是我想出的:

<Style x:Key="IconButtonStyle" TargetType="Button">
    <Style.Resources>
        <Style TargetType="Path">
            <Setter Property="Fill" Value="Black"/> <!-- Default path fill. -->

            <Style.Triggers>
                <!-- How can I set path fill to "Red" based on the parent Button IsEnabled property? -->
            </Style.Triggers>
        </Style>
    </Style.Resources>

    <Style.Triggers>
        <Trigger Property="IsEnabled" Value="false">
            <!-- ?? -->
        </Trigger>
    </Style.Triggers>

</Style>

我的自定义图标按钮具有通过 Style.Resources 定义的默认路径样式。设置默认路径填充很容易,但我不知道如何设置一个触发器,当所有者按钮被禁用时将路径的填充更改为红色。

有可能吗?

好的...我想您需要先修改一些内容才能继续。 首先在 XAML 你应该使用这样的代码:

<Button Style="{DynamicResource IconButtonStyle}" IsEnabled="False" Content="{StaticResource _rect}">
    </Button>

在本例中,我使用了在参考资料中定义的矩形。这是矩形的代码:

    <Rectangle Width="10" Height="10" Style="{StaticResource ContentButtonPathStyle}" x:Key="_rect"></Rectangle>

你显然会使用你的路径而不是矩形... 您注意到样式设置为 ContentButtonPathStyle .

这是该样式的代码:

<Style x:Key="ContentButtonPathStyle" TargetType="{x:Type Rectangle}">
        <Style.Triggers>
            <DataTrigger Binding="{Binding RelativeSource=
                {RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsEnabled}" Value="False">
                <Setter Property="Fill" Value="Red"/>
            </DataTrigger>

            <DataTrigger Binding="{Binding RelativeSource=
                {RelativeSource Mode=FindAncestor, AncestorType={x:Type Button}}, Path=IsEnabled}" Value="True">
                <Setter Property="Fill" Value="Black"/>
            </DataTrigger>
        </Style.Triggers>
    </Style>

请注意,您必须在矩形(路径)之前定义 ContentButtonPathStyle

最后一件事是您甚至不需要为按钮指定样式。除非你需要它用于其他目的。