Search code examples
wpfstylescontrols

How to Apply Theme to Custome Control Inherited from Textbox


I have created a WPF Control That Inherits from a Textbox

I have added Theme BureauBlue to my project and added the following XAML to my Application.xaml

<Application.Resources>
    <ResourceDictionary Source="Themes/BureauBlue.xaml"/>
</Application.Resources>

I want the same theme to be applied to my Custom Control that Inherited from the TextBox

How can I achieve this

Amit Saraf

Edit Changes Made as per suggestion

<Application.Resources>
    <ResourceDictionary Source="Themes/BureauBlue.xaml"/>

    <Style TargetType="WPFControls:MyTextBox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="TextBox">
                    <TextBox Text="{TemplateBinding Text}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Application.Resources>

Error

The property "Resources" can only be set once.
The specified value cannot be assigned. The following type was expected: "ResourceDictionary".

Solution

  • If a Style Targeted to Textbox will not apply for its custom control( control which inherits from Textbox. If you know the BureauBlue's style, place it in your App Resource as a new style which is targeted to your derived class name and if you dont know that style, I can suggest a workaround for this.

    Create a new style targeted to your custom control and define a Template in it as follows

     <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Themes/BureauBlue.xaml" />
            </ResourceDictionary.MergedDictionaries>
            <Style TargetType="WPFControls:MyTextBox">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="TextBox">
                            <TextBox Text="{TemplateBinding Text}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>
    

    Note: Template bind the properties which you tend to use in your custom control class.

    Here the Style which is targeted to Textbox will apply to the your custom control