1

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

4

1 回答 1

4

在单独的类中定义自定义附加属性:

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

然后你可以使用这个:

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

local必须在 XAML 的根元素中定义,大致如下:

xmlns:local="clr-namespace:AttPropTest"

程序集的命名空间在哪里AttPropTest

在代码中,您可以使用 确定 ID Prop.GetID(myRect)

于 2012-06-08T19:35:08.633 回答