3

How come that this ModernUI TextBox

enter image description here

changes its appearance to this

enter image description here

when all that I do is add this style:

<UserControl.Resources>
    <Style TargetType="{x:Type TextBox}">
        <Setter Property="TextAlignment" Value="Right"/>
    </Style>
</UserControl.Resources>

When I set the property directly in the element:

<TextBox Text="" TextAlignment="Right"></TextBox>

Everything looks as it should:

enter image description here

I really don't understand that and would be thankful for a short hint.

peter
  • 2,103
  • 7
  • 25
  • 51

3 Answers3

6

The issue is that it will completely replace the other style.

Add a BasedOn attribute to specify that this style will extend the ModernUI style:

<UserControl.Resources>
    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource whateverModernUIStyleNameIs}">
        <Setter Property="TextAlignment" Value="Right"/>
    </Style>
</UserControl.Resources>

You can also specify the implict style: BasedOn="{StaticResource {x:Type TextBox}}", as pointed out by Mike C.

Read this question for more details: How to apply multiple styles in WPF

Community
  • 1
  • 1
David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • Oh dang David, you beat me by literally seconds lol +1 just for that! – Chris W. Apr 16 '15 at 15:53
  • 1
    That feels so crazy..it works as expected if I, as you write, define the style with TargetType="{x:Type TextBox}" and BasedOn="{StaticResource {x:Type TextBox}}" – peter Apr 16 '15 at 15:53
  • The OP does not have any style applied, and it's implicit. You should also include an example where `BasedOn` is based on the implicit style `{StaticResource {x:Type TextBox}}` – mclark1129 Apr 16 '15 at 15:53
  • @ChrisW. yeah that was very close. Upvote to you too.. I haven't used wpf in over two years. – David Sherret Apr 16 '15 at 15:56
4

By specifying that you're setting a new style template of TargetType of TextBox you're implicitly overriding whatever other style template you have set for it already.

If you add BasedOn to your template to reference the other style giving it the red border it will inherit everything else as it should and only change the property you have your setter for.

So <Style TargetType="{x:Type TextBox}"> then becomes;

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

Make sense? Except why would you need to place a style setter for it, when you already have a property bound to the template to do what you want with one dependency property?

Chris W.
  • 22,835
  • 3
  • 60
  • 94
3

Because you replaced the existing style with one that only sets the text alignment.

Create a style in your Resources based on the default style

<Style
    BasedOn="{StaticResource {x:Type TextBox}}"
    TargetType="{x:Type TextBox}">
    <Setter Property="TextAlignment" Value="Right"/>
</Style>
Frank J
  • 1,666
  • 13
  • 19