Dependency Properties allows you to extend a functionality, from MSDN:

A dependency property provides functionality that extends the functionality of a property as opposed to a property that is backed by a field.

It is used to create bindable properties on objects deriving from DependencyObject, for example in controls. It is used all across WPF.

You can use it as well to create your own bindable properties.

For example:

2015-31-13 05-31-24-043
2015-31-13 05-31-24-043
<local:ExtendedButton DisplayInRed="True"
Content="I'm red" />
<local:ExtendedButton DisplayInRed="False"
Content="I'm NOT red" />

<local:ExtendedButton DisplayInRed="{Binding TrueValue}"
Content="I'm red" />

<Separator />

<local:ExtendedButton2 DisplayInRed="True"
Content="I'm red" />
<local:ExtendedButton2 DisplayInRed="False"
Content="I'm NOT red" />

<!--Error, cannot bind-->
<!--<local:ExtendedButton2 DisplayInRed="{Binding TrueValue}"
Content="I'm red" />-->

You can create a custom actions with properties…

public class ExtendedButton : Button
{
public static readonly DependencyProperty DisplayInRedProperty =
DependencyProperty.Register(nameof(DisplayInRed)
, typeof(bool)
, typeof(ExtendedButton)
, new PropertyMetadata(DisplayInRedChanged));

protected static void DisplayInRedChanged(DependencyObject d,
DependencyPropertyChangedEventArgs ev)
{
bool displayInRed = (bool)ev.NewValue;

if (displayInRed)
{
(d as Button).Background =
new SolidColorBrush(
(Color)ColorConverter.ConvertFromString("red"));
}
}

public bool DisplayInRed
{
get { return (Boolean)this.GetValue(DisplayInRedProperty); }
set { this.SetValue(DisplayInRedProperty, value); }
}
}
// this way it doesn't work with bindings
public class ExtendedButton2 : Button
{
private bool displayInRed;
public bool DisplayInRed
{
get
{
return displayInRed;
}
set
{
displayInRed = value;

if (displayInRed)
{
Background =
new SolidColorBrush(
(Color)ColorConverter.ConvertFromString("red"));
}
}
}
}

The DependencyProperty Register complete method has the following signature:

public static DependencyProperty Register(
string name,
Type propertyType,
Type ownerType,
PropertyMetadata typeMetadata,
ValidateValueCallback validateValueCallback
)
  • name: defines the name of the property it will access

The naming convention is Property for the static definition of the DependencyProperty and then just `` for the actual property.

So if you want to create a custom control and have bindable properties this is the way to do it.

Written by

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store