BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Windows Presentation Foundation
.NET 4.0+

WPF Base Classes - DependencyObject

The nineteenth part of the Windows Presentation Foundation Fundamentals tutorial continues the description of the base classes for the WPF layout controls, which are shared by other controls too. This article describes the DependencyObject class.

Setting a Dependency Property's Local Value

You can change the local value of a property using the SetValue method. Of course, this method does not guarantee that the control will be updated to show the specified value, as styles or animations may come into effect. When setting a local value you provide the dependency property field and the new value to the SetValue method of the control that is to be affected. The syntax is as follows:

control.SetValue(dependency-property, value);

To demonstrate, let's make a change to the existing example. Replace the content of ButtonClick with the sample code below. The first line reads the button's current column number and subtracts this from one to find the number of the unused column. The second line sets the Grid.Column property of the button to the calculated value, causing the button to switch columns with each click.

Try running the code and clicking the button several times to see the effect.

int newColumn = 1 - (int)MyButton.GetValue(Grid.ColumnProperty);
MyButton.SetValue(Grid.ColumnProperty, newColumn);

Clearing a Dependency Property's Local Value

After setting a local value for a property you may wish to return to the default. Rather than setting the default value explicitly, you can clear the local value using the ClearValue method. Following the pattern of the other methods we've seen, you provide the field representing the dependency property as the method's only argument.

Change the code in the ButtonClick method for one last time to demonstrate. The new code gives the same behaviour as the previous example. In this case it works by finding the button's current column. If it is set to zero, the local value is explicitly set to one. If the value is not zero, the local value is cleared. Clearing the local value moves the button into column zero, due to this being the default position.

int current = (int)MyButton.GetValue(Grid.ColumnProperty);

if (current == 0)
    MyButton.SetValue(Grid.ColumnProperty, 1);
else
    MyButton.ClearValue(Grid.ColumnProperty);
26 June 2013