簡體   English   中英

WPF ControlTemplate 從父資源繼承樣式

[英]WPF ControlTemplate inherit style from parent resources

我正在使用樣式“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 中使用 LinkBut​​ton,則不會應用該樣式。 有沒有辦法讓 ControlTemplate 繼承 FooterPanel 中的樣式而不是任何全局超鏈接樣式?

編輯:

根據這個答案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樣式中指定的顏色。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM