繁体   English   中英

如何在后面的代码中将自定义样式应用于自定义控件

[英]How to apply a customized style to a custom control in code behind

我有一个简单的自定义控件:

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

还有一个自定义样式,使控件看起来像TextBlock(在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>

但是,当我在应用程序中使用它时,它根本不会显示。 如果我删除它,它会像普通的TextBox一样显示this.DefaultStyleKey = typeof(ReadOnlyTextBox);

如何在后面的代码中将此样式应用于我的自定义控件?

顺便说一句,这种样式在带有Style="{StaticResource ReadOnlyTextBox}" xaml中很好用,但是在这种情况下我不能使用xaml。

提前致谢。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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