Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom control not inheriting parent's styles

I'm trying to maintain a uniform look and feel across elements in my WPF application, and at the same time I want to create a modified TextBox. However, when I do this, styles that I define at the application level for TextBox aren't being applied to the class I created, even though the style created for my custom control is using the BasedOn property.

Is there something I'm missing that's causing this to behave differently than I expect?

I reproduced the issue in a brand-new WPF project in VS2010 with this setup:

C# Code:

public class CustomTextBox : TextBox
{
    static CustomTextBox() {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomTextBox), new FrameworkPropertyMetadata(typeof(CustomTextBox)));
    }
}

XAML in Themes\Generic.xaml:

<Style TargetType="{x:Type local:CustomTextBox}" BasedOn="{StaticResource {x:Type TextBox}}"/>

XAML in App.xaml:

<Application.Resources>
    <Style TargetType="TextBox">
        <Setter Property="Background" Value="Red"/>
    </Style>
</Application.Resources>

However, in the designer and when I run the app, the CustomTextBox falls back onthe default styling for the text box instead of having a red background, even though the documentation for the BasedOn property suggests that my derived class should have this styling...

There are several ways that styles in WPF can be extended or inherited. Styles can be based on other styles through this property. When you use this property, the new style will inherit the values of the original style that are not explicitly redefined in the new style.

...

Note: If you create a style with a TargetType property and base it on another style that also defines a TargetType property, the target type of the derived style must be the same as or be derived from the type of the base style.

like image 766
p0lar_bear Avatar asked Oct 31 '22 02:10

p0lar_bear


1 Answers

Short Answer: Your style is based on a StaticResource

<Style TargetType="{x:Type local:CustomTextBox}" BasedOn="{StaticResource {x:Type TextBox}}"/>

When you did this, you are not changing the StaticResource

<Style TargetType="TextBox">
    <Setter Property="Background" Value="Red"/>
</Style>

So CustomTextBox is not supposed to inherit the red background.

like image 67
user2880486 Avatar answered Dec 19 '22 00:12

user2880486