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

本文关键字:属性 自己的 创建 样式 我可以 | 更新日期: 2023-09-27 18:37:24

我想在一种风格中正确地创建自己的风格,可以吗?

我有叶翼风格

<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>

我想添加一个名为"操作"的属性...

有人知道这是否可能吗?

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

如果要

将另一个属性添加到"文本框",则需要扩展该类,例如:

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" />

依赖项属性使你可以从 XAML 编辑它,对象属性是这样你可以从 C# 访问它。