Thursday, December 11, 2008

[C#] Creating Custom Dependency Properties

Oh! I'm so excited... I think I actually got this to work for me :)
Please note that this is for creating simple DependencyProperties... I am not creating an attached property here.

I have a custom user control called GraphicGrid which consists of multiple line elements that draw up a grid. I also have a custom user control called PropertyEditor which allows for easy changes to specific DependencyProperties of a given object. I wanted to be able to change the grid color and grid spacing via the editor, so I decided this was the perfect chance to try and implement custom dependency properties.

Here are the basic steps to setting one up:

Step 1:
Register the custom dependency property. Here I create a new dependency propery and give it a name, what the property type is, what the owning object type is, and then in my case, I register a callback to be ran when the value is changed. Note that you do not need to setup a callback function [use null instead], unless you need specific things to happen when the value is changed:
public static readonly DependencyProperty GridLineStrokeProperty =
DependencyProperty.Register("GridLineStroke",
typeof(Brush),
typeof(GraphicGrid),
new PropertyMetadata(GridLineStrokeChanged));

Step 2 [if you setup a callback]:
If you have setup a callback if the value has been changed, then you need to create that function.
private static void GridLineStrokeChanged(DependencyObject o,
DependencyPropertyChangedEventArgs e)

{
GraphicGrid grid = o as GraphicGrid;

// Color lines.
foreach (UIElement line in grid.LayoutRoot.Children)
{
line.SetValue(Shape.StrokeProperty, e.NewValue);
}
}

Here, I cast the sender to a GraphicGrid, which I believe is acceptable since I have registered the property to GraphicGrid. Then I perform some actions with the new value... in my case I update all the lines in the grid with the new color.

Step 3:
Then, if you wish, you can create a local variable which gets and sets this dependency property.
public Brush GridLineStroke
{
get { return (Brush)GetValue(GridLineStrokeProperty); }
set { SetValue(GridLineStrokeProperty, value); }
}
Step 4:
Update the property at your will and whenever the value is changed, the line color will also be changed!


Update directly via the DependencyProperty:
GraphicGrid newGrid = new GraphicGrid ();
newGrid.SetValue(GraphicGrid.GridLineStrokeProperty,
new SolidColorBrush(Colors.Red));



Update via the local variable:
newGrid.GridLineStroke = new SolidColorBrush(Colors.Red);



BAM! Auto updating lines!!!
Special thanks to bryant on the Silverlight forums :)
.

No comments: