我可以在样式中创建自己的属性吗?

时间:2013-10-30 12:07:36

标签: c# xaml

我想以一种风格正确地创造自己的风格,是否可能?

我有fol风格

<Style x:Key="EditTextBox" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="TextWrapping" Value="Wrap"/>
    <Setter Property="AcceptsReturn" Value="True"/>
    <Setter Property="VerticalScrollBarVisibility" Value="Auto"/>
</Style>

我要添加一个名为'OPERATION'的属性...     

有人知道这是否可能?

1 个答案:

答案 0 :(得分:4)

如果要将另一个属性添加到“TextBox”,则需要扩展该类,例如:

public class CustomTextBox : TextBox
{
    public static readonly DependencyProperty OperationProperty = 
        DependencyProperty.Register(
            "Operation", //property name
            typeof(string), //property type
            typeof(CustomTextBox), //owner type
            new FrameworkPropertyMetadata("Default value")
        );
    public string Operation
    {
        get
        {
            return (string)GetValue(OperationProperty);
        }
        set
        {
            SetValue(OperationProperty, value);
        }
    }
}

然后您可以设置自定义文本框样式:

<Style x:Key="EditTextBox" TargetType="{x:Type CustomTextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="Operation" Value="string value"/>
</Style>

<my:CustomTextBox Operation="My value" Text="You can still use it as a textbox" />

DependencyProperty是您可以从XAML编辑它的对象属性,因此您可以从C#访问它。

相关问题