Edwin
Edwin

Reputation: 961

Style breaks when x:Key is added

Under <Window.Resources>, I have the following style defined:

    <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>

It works fine until I needed to inherit the style on another style

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

Which means I need to add the x:Key=TextBoxStyle to the Text box style above.
But when I do this, the styling for the text box breaks altogether.
I tried doing the same to Button styling, and the same thing happens, where the style will break if I add a key to it.

The only solution I thought of is to individually add the style to the elements, but that is what I am trying not to do.

Upvotes: 0

Views: 167

Answers (2)

DHN
DHN

Reputation: 4865

Well to provide a better understandability and maintainance, I would prefer the following approach. IMHO, another programmer could get better into the code, if the implicities are reduced to a minimum.

<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>

Just my two cents...

Upvotes: 0

brunnerh
brunnerh

Reputation: 184554

No, you do not need to add x:Key to reference it:

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

Upvotes: 2

Related Questions