WPF 控件模板从父资源继承样式



我正在设置出现在边框内的超链接样式,样式为"FooterPanel",如下所示:

<Style x:Key="FooterPanel" TargetType="{x:Type Border}">
    <Style.Resources>
        <Style TargetType="{x:Type Hyperlink}">
            <Setter Property="Foreground" Value="{StaticResource FooterPanelLinkBrush}"/>
        </Style>
    </Style.Resources>
</Style>

我现在还创建了一个样式来创建一个按钮作为超链接(因此我可以在超链接上获取 IsDefault 和 IsCancel 等属性):

<Style x:Key="LinkButton" TargetType="{x:Type Button}">
    <Setter Property="Focusable" Value="False"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
                    <Hyperlink Command="{TemplateBinding Command}" CommandParameter="{TemplateBinding CommandParameter}">
                        <Run Text="{TemplateBinding Content}"/>
                    </Hyperlink>
                </TextBlock>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
FooterPanel

中的普通超链接接收 FooterPanelLinkBrush 前景,但是如果我在 FooterPanel 中使用 LinkButton,则不会应用样式。有没有办法让控件模板继承页脚面板中的样式而不是任何全局超链接样式?

编辑:

根据这个答案 https://stackoverflow.com/a/9166963/2383681 有特殊的处理,这意味着Hyperlink不会收到FooterPanel中定义的样式,因为它不是从Control派生的。

不确定如果没有一些代码隐藏,我正在尝试做什么是可能的,所以我想我只是要解决这个问题并为FooterPanelLinkButton创建一个新样式,并为页脚面板中的按钮显式引用它。知道这是否可能很有趣,但是如果不这样做。

您可以

HyperLink创建一个单独的Style

<Style x:Key="FooterPanelLink" TargetType="{x:Type Hyperlink}">
    <Setter Property="Foreground" Value="{StaticResource FooterPanelLinkBrush}"/>
</Style>

然后按以下方式在FooterPanelLinkButton样式的Resources中使用此Style

<Style x:Key="FooterPanel" TargetType="{x:Type Border}">
    <Style.Resources>
        <Style TargetType="Hyperlink" BasedOn="{StaticResource FooterPanelLink}" />
    </Style.Resources>
</Style>
<Style x:Key="LinkButton" TargetType="{x:Type Button}">
    <Style.Resources>
        <Style TargetType="Hyperlink" BasedOn="{StaticResource FooterPanelLink}" />
    </Style.Resources>
    <Setter Property="Focusable" Value="False"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center">
                    <Hyperlink Command="{TemplateBinding Command}" CommandParameter="{TemplateBinding CommandParameter}">
                        <Run Text="{TemplateBinding Content}"/>
                    </Hyperlink>
                </TextBlock>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

这样,LinkButton内的HyperLink将使用您在FooterPanelLink样式中分配的颜色。

最新更新