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

amit kohan
  • 1,612
  • 2
  • 25
  • 47

1 Answers1

4

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

  • Hi Fmunkert, it was a great sample so I followed all the steps but I guess something I'm missing here cause when I run it i get an error as (in XAML) **Cannot convert the value in attribute 'Property' to object of type 'System.Windows.DependencyProperty'. ** – amit kohan Jun 08 '12 at 23:06