Wpf 添加x:Key时,样式会中断

Wpf 添加x:Key时,样式会中断,wpf,xaml,Wpf,Xaml,在下,我定义了以下样式: <Style TargetType="TextBox"> <Setter Property="Height" Value="22" /> <Setter Property="Width" Value="125" /> <Setter Property="HorizontalAlignment" Value="Left" /> <Setter Pr

下,我定义了以下样式:

    <Style TargetType="TextBox">
        <Setter Property="Height" Value="22" />
        <Setter Property="Width" Value="125" />
        <Setter Property="HorizontalAlignment" Value="Left" />
        <Setter Property="VerticalAlignment" Value="Top" />
        <Setter Property="Foreground" Value="Black" />
        <Setter Property="Background" Value="WhiteSmoke" />
    </Style>

在我需要在另一个样式上继承该样式之前,它可以正常工作

<Style BasedOn="{StaticResource TextBoxStyle}" TargetType="{x:Type PasswordBox}">

这意味着我需要将
x:Key=TextBoxStyle
添加到上面的文本框样式中。
但当我这样做时,文本框的样式会完全中断。
我试着对按钮样式做同样的处理,同样的事情也发生了,如果我给它添加一个键,样式就会中断


我想到的唯一解决方案是将样式单独添加到元素中,但这正是我不想做的。

不,您不需要添加
x:Key
来引用它:

<Style BasedOn="{StaticResource {x:Type TextBox}}" TargetType="{x:Type PasswordBox}">

为了提供更好的可理解性和可维护性,我更喜欢以下方法。IMHO,如果隐式降低到最低限度,另一个程序员可以更好地理解代码

<Style x:Key="BasicTextBoxStyle" TargetType="{x:Type TextBox}">
    <!--some settings here-->
</Style>

<!--Declare BasicTextBoxStyle as default style for TextBoxes-->
<Style BasedOn="{StaticResource BasicTextBoxStyle}" TargetType="{x:Type TextBox}"/>

<!--Create some special style based on the basic style-->
<Style BasedOn="{StaticResource BasicTextBoxStyle}" TargetType="{x:Type PasswordBox}">
    <!--some more specific settings-->
</Style>


就我的两分钱…

我明白了。不过我还是很好奇,为什么在我添加键时样式会中断?@Edwin:它不会中断,如果您不指定
x:key
该键被设置为控件的类型,这使得它适用于该类型的所有控件,您也可以手动执行此操作。如果指定另一个键,它不会自动应用。