【问题标题】:How to apply a customized style to a custom control in code behind如何在后面的代码中将自定义样式应用于自定义控件
【发布时间】:2012-01-19 23:07:24
【问题描述】:

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

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>

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

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

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

提前致谢。

【问题讨论】:

    标签: c# silverlight windows-phone-7


    【解决方案1】:
    this.Style = (Style)Application.Current.Resources["ReadOnlyTextBox"];
    

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

    【讨论】:

    • 或标准控件:yourControl.Style = (Style)App.Current.Resources["x:key of your style in Application.Ressources"];Source
    猜你喜欢
    • 1970-01-01
    • 2019-12-17
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-20
    • 2016-07-29
    相关资源
    最近更新 更多