How to write a Dependency property in WPF

By samjayander thiagarajan

How write a new (basic) dependency in WPF.

Step 1:
Derive your class in which you want the dependency property from DependencyObject

public class SomeClass : DependencyObject
{}


Step 2:
If you want to have property names, someName, then register a dependency property naming it - someName suffixed Property. So in our case, someNameProperty

public class SomeClass : DependencyObject
{
public static readonly DependencyProperty someNameProperty =
      DependencyProperty.Register("SomeName", typeof(string), typeof(SomeClass));
}


In the above example, the Register function has three arguments:
1. "SomeName" -> it is the unique name used for registering the dependency property
2. typeof(string) -> the type of the dependency property
3. typeof(SomeClass) -> the type of the class owning the property

Step 3:
Introduce a member which will expose the dependency property. In our case, its name should be "SomeName" as decided earlier..

public class SomeClass : DependencyObject
{
public static readonly DependencyProperty someNameProperty =
      DependencyProperty.Register("SomeName", typeof(string), typeof(SomeClass));

  public string SomeName
  {
    get
    {
      return (string)GetValue(someNameProperty);
    }
    set
    {
      SetValue(someNameProperty, value);
    }
}
}

Thats it!!!

How to write a Dependency property in WPF  (928 Views)