Mualig
Mualig

Reputation: 1444

How to apply a customized style to a custom control in code behind

I've got a simple custom control :

namespace Application.Custom_Controls
{
    public class ReadOnlyTextBox : TextBox
    {
        public ReadOnlyTextBox()
        {
            this.DefaultStyleKey = typeof(ReadOnlyTextBox);
            this.IsReadOnly = true;
        }
    }
}

And a custom style to make the control look like a TextBlock (in App.xaml).

<Application 
    x:Class="Application.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"       
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:tb = "clr-namespace:Application.Custom_Controls"
    >

    <!--Application Resources-->
    <Application.Resources>
        <Style x:Key="ReadOnlyTextBox" TargetType="tb:ReadOnlyTextBox">
            //...
            <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="tb:ReadOnlyTextBox">
                    //...
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

But when I'm using it in my application it does'nt display at all. It diplays as a normal TextBox if I remove this.DefaultStyleKey = typeof(ReadOnlyTextBox);.

How to apply this style to my custom control in code behind ?

By the way, this style works well in xaml with Style="{StaticResource ReadOnlyTextBox}", but I can't use xaml in this case.

Thanks in advance.

Upvotes: 0

Views: 3252

Answers (1)

Divya
Divya

Reputation: 2622

this.Style = (Style)Application.Current.Resources["ReadOnlyTextBox"];

Add this line to the constructor of the ReadOnlyTextBox

Upvotes: 5

Related Questions