简体   繁体   中英

Can I create my own properties in styles?

I want to create my own properly in a style, is it possible?

I have the foliwing style

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

and I want to add a property that is called 'OPERATION'...

Anybody know if that is possible?

If you want to add another property to a 'TextBox' you need to extend the class, for example:

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);
        }
    }
}

Then you can set your custom textbox style:

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

Or

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

The DependencyProperty is so you can edit it from XAML and the object property is so you can access it from C#.

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