简体   繁体   中英

How to create a custom property?

I need to create a custom property meaning rather using

<Style x:Key="ABC" TargetType="Rectangle">
    <Setter Property="Fill" Value="Red"/>
</Style>

I like to have something like Rectangle and assign it an ID so later when it is dropped on Canvas I can retrieve its ID.

<Style x:Key="ABC" TargetType="Rectangle">
    <Setter Property="Fill" Value="Red"/>
    **<Setter Property="ID" Value="1234567890-ABC"/>**
</Style>

How can I define that custom property?

Regards, Amit

Define a custom attached property in a separate class:

public class Prop : DependencyObject
{
    public static readonly DependencyProperty IDProperty =
        DependencyProperty.RegisterAttached("ID", typeof(string), typeof(Prop), new PropertyMetadata(null));

    public static void SetID(UIElement element, string value)
    {
        element.SetValue(IDProperty, value);
    }

    public static string GetID(UIElement element)
    {
        return (string)element.GetValue(IDProperty);
    }
}

Then you can use this:

<Setter Property="local:Prop.ID" Value="1234567890-ABC"/>

local must be defined in the root element of your XAML appromimately like this:

xmlns:local="clr-namespace:AttPropTest"

where AttPropTest is the namespace of the assembly.

In code, you can determine the ID with Prop.GetID(myRect) .

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