应用默认WPF样式

xan*_*ont 10 wpf styles

我有一个全球性的风格,将我所有的TextBox风格,但在某些情况下,我想恢复只是前景色到原来的非定制式的色彩.我尝试使用我希望恢复{TemplateBinding Foreground}的特定内部TextBoxes.它最终不是有效的XAML,我不确定这是正确的方式.

有任何想法吗?谢谢.

rmo*_*ore 11

有几种方法可以做到这一点.如果查看MSDN 上的Precedence List,则可以看到1-8中的Forground设置将覆盖Foreground默认样式.最简单的方法就是设置本地值TextBox.

<TextBox Foreground="Red" />
Run Code Online (Sandbox Code Playgroud)

您可以做的另一件事是使用'BasedOn'样式的属性来覆盖其他版本.这确实需要为您的默认样式提供一个键值,但是这可以用于应用默认样式,如下例所示:

    <Style TargetType="{x:Type TextBox}"
           x:Key="myTextBoxStyle">
        <Setter Property="Foreground"
                Value="Red" />
        <Setter Property="FontWeight"
                Value="Bold" />
    </Style>
    <!-- Style applies to all TextBoxes -->
    <Style TargetType="{x:Type TextBox}"
           BasedOn="{StaticResource myTextBoxStyle}" />


<TextBox Text="Hello">
    <TextBox.Style>
        <Style BasedOn="{StaticResource myTextBoxStyle}" TargetType="{x:Type TextBox}">
            <Setter Property="Foreground"
                    Value="Blue" />
        </Style>
    </TextBox.Style>
</TextBox>
Run Code Online (Sandbox Code Playgroud)


编辑:
如果默认样式正在应用某个值,并且您希望将其还原为基值,那么我可以通过几种方式来考虑这种行为.我知道,您不能以通用方式绑定回默认主题值.

然而,我们可以做一些其他的事情.如果我们需要样式不应用某些属性,我们可以将样式设置为{x:Null},从而停止应用默认样式.或者我们可以为元素提供不依赖于基本样式的自己的样式,然后仅重新应用我们需要的setter:

        <TextBox Text="Hello" Style="{x:Null}" />
        <TextBox Text="Hello">
            <TextBox.Style>
                <Style TargetType="{x:Type TextBox}">
                    <Setter Property="FontWeight"
                            Value="Bold" />
                </Style>
            </TextBox.Style>
        </TextBox>
Run Code Online (Sandbox Code Playgroud)

我们可以修改默认样式,以便Foreground仅在某些条件下设置,例如Tag是某个值.

    <Style TargetType="{x:Type TextBox}"
           x:Key="myTextBoxStyle">
        <Setter Property="FontWeight"
                Value="Bold" />
        <Style.Triggers>
            <Trigger Property="Tag"
                     Value="ApplyForeground">
                <Setter Property="Foreground"
                        Value="Red" />
            </Trigger>
        </Style.Triggers>
    </Style>

   <TextBox Text="Hello" />
    <TextBox Text="Hello" Tag="ApplyForeground" />
Run Code Online (Sandbox Code Playgroud)