让DrawingImage继承包含Button的颜色

时间:2017-05-19 18:52:03

标签: wpf xaml wpf-style

我有一些具有共同风格的按钮。此样式有ContentPresenter,在按钮声明中填充DrawingImage

DrawingImage使用预定义画笔时,此功能正常。但是我非常希望我的DrawingImage使用样式中使用的Foreground颜色,或者如果在那里覆盖它,则使用按钮。

我该如何做到这一点?

我目前的风格:

<UserControl.Resources>
    <DrawingImage x:Key="SomeIcon">
        <DrawingImage.Drawing>
            <DrawingGroup>
                <DrawingGroup>
                    <GeometryDrawing Brush="White" Geometry="PATH" />
                    <GeometryDrawing Brush="White" Geometry="OTHER_PATH" />
                </DrawingGroup>
            </DrawingGroup>
        </DrawingImage.Drawing>
    </DrawingImage>

    <Style x:Key="MyButton" TargetType="{x:Type Button}">
        <Setter Property="Foreground" Value="Blue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <ContentPresenter/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Resources>
<Grid>
    <Button Style="{StaticResource MyButton">
        <!-- I want this icon to be Blue as inherited from the style. -->
        <Image Source="{StaticResource SomeIcon}"/>
    </Button>
    <Button Style="{StaticResource MyButton" Foreground="Red">
        <!-- I want this icon be Red as overriden by the button -->
        <Image Source="{StaticResource SomeIcon}"/>
    </Button>
</Grid>

我只想要纯XAML答案。我们也非常感谢其他针对同一目标的XAML路线,例如使用Path代替DrawingImage

1 个答案:

答案 0 :(得分:1)

您可以将图标资源声明为几何图形,并使用具有如下路径的按钮样式:

<Window.Resources>
    <Geometry x:Key="SomeIcon">M0,20 L20,0 40,20 20,40Z</Geometry>
    <Style x:Key="PathButtonStyle" TargetType="Button">
        <Setter Property="Foreground" Value="Blue"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                <ControlTemplate TargetType="Button">
                    <Path Fill="{TemplateBinding Background}"
                          Stroke="{TemplateBinding Foreground}"
                          Data="{TemplateBinding Content}"
                          Stretch="None"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <Button Style="{StaticResource PathButtonStyle}" 
            Content="{StaticResource SomeIcon}"/>
</Grid>