Simplest WPF Dependency Property For Beginners On Background Color

Perhaps you know what is a Dependency Property and how it is more advanced than native CLR properties. If not, let me know. I will try to explain.

FYI

Dependency Property is not wrapped over any private members unlike CLR properties, and it is also stored in Key-Value pairs inside the DependencyObject host instance. You must use Dependency properties if you need to create and apply properties on custom user controls, or change properties based on external inputs like Theme, Style, animation etc. or while applying the data binding or set with a resource (static/dynamic).
 
Now, I will try to create a dependency property which will help you begin implementation in WPF.
 
First, create a project of type WPFApplication in Visual Studio with name DependencyPropertyTutorial. As we haven't yet created any user control, so our next step is to create a custom User Control in WPF.
 
Add a new item of type UserControl(WPF) to the project and give the name CustomButtonControl. We will now embed a button inside this control through code. Name of the button is btnCustom.
 
xaml code: CustomButtonControl.xaml
  1. <UserControl x:Class="DependencyPropertyTutorial.CustomButtonControl" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:DependencyPropertyTutorial" mc:Ignorable="d" d:DesignHeight="100" d:DesignWidth="100">  
  2.     <Grid>  
  3.         <Button x:Name="btnCustom" Content="Button" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="75" Height="52" Click="btnCustom_Click" /> </Grid>  
  4. </UserControl>  
The basic essence of Dependency Property is that we can create these custom dependency properties for our custom user controls. That's why we have created this user control in order to test the dependency property in it.
 
Till now, I haven't created any dependency property.

Now, I will.
 
In the code-behind: CustomButtonControl.xaml.cs,
  1. using...namespace DependencyPropertyTutorial {  
  2.     /// <summary>  
  3.     /// Interaction logic for CustomButtonControl.xaml  
  4.     /// </summary>  
  5.     public partial class CustomButtonControl: UserControl {  
  6.         public CustomButtonControl() {  
  7.             InitializeComponent();  
  8.         }  
  9.         public static readonly DependencyProperty btnDependencyProperty = DependencyProperty.Register("SetBackground"typeof(SolidColorBrush), typeof(CustomButtonControl), new PropertyMetadata(new SolidColorBrush(Colors.HotPink), new PropertyChangedCallback(OnSetColorChanged)));  
  10.         public SolidColorBrush SetBackground {  
  11.             set {  
  12.                 SetValue(btnDependencyProperty, value);  
  13.             }  
  14.             get {  
  15.                 return (SolidColorBrush) GetValue(btnDependencyProperty);  
  16.             }  
  17.         }  
  18.         private void btnCustom_Click(object sender, RoutedEventArgs e) {  
  19.             this.SetBackground = new SolidColorBrush(Colors.IndianRed);  
  20.         }  
  21.         private static void OnSetColorChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {  
  22.             CustomButtonControl mycontrol = d as CustomButtonControl;  
  23.             mycontrol.callmyInstanceMethod(e);  
  24.         }  
  25.         private void callmyInstanceMethod(DependencyPropertyChangedEventArgs e) {  
  26.             btnCustom.Background = (SolidColorBrush) e.NewValue;  
  27.         }  
  28.     }  
  29. }  
Explanation

Custom Dependency property is created using DependencyProperty.Register() method which takes few arguments --> Name of the property, Type of the values the property accepts,  Type of the owner that hosts the property, and a PropertyMetadata instance with DefaultValue and PropertyChangedCallback parameters set. DefaultValue is the default value the property holds. And, PropertyChangedCallback represents the callback that is invoked when the effective property value of this dependency property changes.

Now, as explained earlier, the dependency property is wrapped around the inner DependencyObject implementation using a set of getter & setter methods.

When the dependency property value is about to change,  OnSetColorChanged() is called. But as its a static method, so we needed to create an instance of the UserControl and then call any of its Instance method (here its callmyInstanceMethod), where we can reference its embedded Button and set its Background.

Notice how we cast DependencyObject as CustomButtonControl, and how we used DependencyPropertyChangedEventArgs i.e., NewValue and cast to SolidBrushColor which is the type of the dependency property. 
 
Our UserControl alongwith the Dependency property is ready for use. Now its time to test it.
 
Let's come down to the MainWindow.xaml where we will include this User Control and set its Dependency Property with an appropriate value.
 
MainWindow.xaml
  1. <Window x:Class="DependencyPropertyTutorial.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:views="clr-namespace:DependencyPropertyTutorial" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:DependencyPropertyTutorial" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525">  
  2.     <Window.Resources>  
  3.         <SolidColorBrush x:Key="BG" Color="Green" /> </Window.Resources>  
  4.     <Grid>  
  5.         <views:CustomButtonControl SetBackground="{DynamicResource BG}"></views:CustomButtonControl>  
  6.     </Grid>  
  7. </Window>  
Explanation

Pretty simple and self-explanatory. Just a thing for newbies- In WPF, if you are not so familiar with WPF resources, just read about Window.Resources. We set a SolidColorBrush with Color Green as this WPF Windows resource. Now, we can access this resource throughout the XAML. In the Grid, we have put a CustomButtonControl and called the DependencyProperty SetBackground with value {DynamicsResource BG}. This is also known as WPF Binding and it gets the value dynamically (i.e. at runtime) from the resource we defined.
 
Now guys, you can download the source code or copy-paste the source code given here and compile. It will compile with no issues. Then, run it.

Start painting the buttons with your favorite colors. 
Ebook Download
View all
Learn
View all