首页 > 解决方案 > WPF,按钮继承 Foreground 的内容

问题描述

问题:如何设计按钮,它继承Foreground自其父级,但允许通过样式更改它?

更准确地说,给定以下按钮:

<StackPanel TextBlock.Foreground="Red">
<ToggleButton Width="16" Height="16" FontSize="10" Style="{StaticResource ...}">
    <Grid>
        <Path Width="8" Height="8" Fill="...">
            <Path.Data>
                <PathGeometry Figures="M 1 0 L 1 4 L 0 4 L 0 5 L 3 5 L 3 8 L 4 8 L 4 5 L 7 5 L 7 4 L 6 4 L 6 0 L 1 0 z M 2 1 L 4 1 L 4 4 L 2 4 L 2 1 z " FillRule="NonZero"/>
            </Path.Data>
        </Path>
    </Grid>
</ToggleButton>
</StackPanel>

我需要它:

我尝试设计按钮的样式,包括ControlTemplate,但Foreground. Button 通过主题将其Foreground属性设置为某些,因此它与'sDynamicResource不匹配。StackPanelForeground

显然我可以绑定它,但随后样式和控制模板触发器停止工作,因为我已经为依赖属性设置了一个立即值,这推翻了所有其他为其提供值的方法。

为了给出问题的背景,这就是我想要实现的目标:

在此处输入图像描述

标签: wpfwpf-style

解决方案


您可以像这样绑定到父TextBlock.Foreground级的附件:ToggleButtonPanel

<Path Width="8" Height="8"
       Fill="{Binding (TextBlock.Foreground), 
           RelativeSource={RelativeSource AncestorType=Panel, AncestorLevel=2}}">
...

如果你想Fill在鼠标悬停时改变,你可以Style用 a 定义 a DataTrigger

<StackPanel TextBlock.Foreground="Red">
    <ToggleButton Width="16" Height="16" FontSize="10">
        <Grid>
            <Path Width="8" Height="8">
                <Path.Data>
                    <PathGeometry Figures="M 1 0 L 1 4 L 0 4 L 0 5 L 3 5 L 3 8 L 4 8 L 4 5 L 7 5 L 7 4 L 6 4 L 6 0 L 1 0 z M 2 1 L 4 1 L 4 4 L 2 4 L 2 1 z "
                                  FillRule="NonZero"/>
                </Path.Data>
                <Path.Style>
                    <Style TargetType="Path">
                        <Setter Property="Fill" Value="{Binding (TextBlock.Foreground), 
                     RelativeSource={RelativeSource AncestorType=Panel, AncestorLevel=2}}" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding IsMouseOver, 
                    RelativeSource={RelativeSource AncestorType=ToggleButton}}" Value="True">
                                <Setter Property="Fill" Value="Blue" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </Path.Style>
            </Path>
        </Grid>
    </ToggleButton>
</StackPanel>

推荐阅读