简体   繁体   中英

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.

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

将此行添加到ReadOnlyTextBox的构造函数中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM