Dependency properties in WPF

In This blog, I will try to give walk through a simple example, showing you how to create a user control, add dependency properties, and wire up them to the user control XAML.

Dependency properties have come as a basic feature of WPF in its initial release 2006 with .net framework 3.0, this version is also known as wpf3.0 and its code name was Avalon.

Well, before the start, it is needed to have a brief about Dependency property, because the main objective of this post is to understand dependency properties of WPF’s new property systems.This property system (dependency property) almost the same as CLR property system. According to msdn ‘‘the purpose of dependency properties is to provide a way to compute the value of a property based on the value of other inputs. These other inputs might include system properties such as themes and user preference, just-in-time property determination mechanisms such as data binding and animations/storyboards, multiple-use templates such as resources and styles, or values known through parent-child relationships with other elements in the element tree. In addition, a dependency property can be implemented to provide self-contained validation, default values, callbacks that monitor changes to other properties, and a system that can coerce property values based on potentially runtime information. Derived classes can also change some specific characteristics of an existing property by overriding dependency property metadata, rather than overriding the actual implementation of existing properties or creating new properties”.

So we can say dependency properties depend on multiple providers or external resources for determining its value at any point in time. The value of a Dependency Property is resolved dynamically. Major advantages have by dependency properties are reduced memory footprint, value inheritance and change notification.

So let’s have a quick start to writing code regarding this by creating a new WPF project in our visual studio.

Create WPF project

Now going to create User control (similar Label control) with display or not display mandatory symbol just after the text of the label. I am creating three dependency properties for achieving the same and have proper understanding, how can we use them.

IsRequired :- for display mandatory symbol.

RequiredSymbol :- for which symbol use as mandatory symbol

LabelText :- Text of control.

Add new user control in wpf project

In the Below picture, I have registered three dependency properties for my user control in code behind.

register dependency properties in wpf

    public partial class IsMandatoryLabelControl : UserControl
     {
         public IsMandatoryLabelControl()
         {
             InitializeComponent();
         }
 
         public string RequiredSymbol
         {
             get { return (string)GetValue(RequiredSymbolProperty); }
             set { SetValue(RequiredSymbolProperty, value); }
         }
 
         public static readonly DependencyProperty RequiredSymbolProperty =
              DependencyProperty.Register("RequiredSymbol", typeof(string), typeof(IsMandatoryLabelControl), new PropertyMetadata("*"));
 
         public string LabelText
         {
             get { return (string)GetValue(LabelTextProperty); }
             set { SetValue(LabelTextProperty, value); }
         }
 
         public static readonly DependencyProperty LabelTextProperty =
             DependencyProperty.Register("LabelText", typeof(string), typeof(IsMandatoryLabelControl), new PropertyMetadata(string.Empty));
 
         public bool IsRequired
         {
             get { return (bool)GetValue(IsRequiredProperty); }
             set { SetValue(IsRequiredProperty, value); }
         }
 
         public static readonly DependencyProperty IsRequiredProperty =
                    DependencyProperty.Register("IsRequired", typeof(bool), typeof(IsMandatoryLabelControl), new PropertyMetadata(true, OnRequiredChange));
 
         private static void OnRequiredChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
         {
             IsMandatoryLabelControl ctrl = d as IsMandatoryLabelControl;
             if ((bool)e.NewValue == false)
                 ctrl.RequiredSymbol = string.Empty;
         }
     }

Now, I am adding to label control within stackpanal in my user control and bind the values to my dependency properties

Dependency properties for user control

<UserControl x:Class="WpfApp3.IsMandatoryLabelControl" x:Name="MandatoryLabel" 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:WpfApp3" mc:Ignorable="d" d:DesignHeight="450" d:DesignWidth="800"> <StackPanel Orientation="Horizontal"> <TextBlock Text="{Binding Path=LabelText,ElementName=MandatoryLabel}" /> <TextBlock Text="{Binding Path=RequiredSymbol,ElementName=MandatoryLabel}" Foreground="Red" /> </StackPanel> </UserControl>

Now put IsMandatoryLabelControl in MainWindow and assign those three dependency properties some values.

Dependencey properties advantage

<Window x:Class="WpfApp3.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp3" mc:Ignorable="d" Title="MainWindow" Height="200" Width="500"> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="2*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="auto"/> <RowDefinition Height="auto"/> <RowDefinition Height="auto"/> </Grid.RowDefinitions> <local:IsMandatoryLabelControl Grid.Row="0" Grid.Column="0" IsRequired="True" LabelText="Name" RequiredSymbol="*" Margin="10"/> <TextBox Grid.Row="0" Grid.Column="1" Margin="10 5"></TextBox> <local:IsMandatoryLabelControl Grid.Row="1" Grid.Column="0" IsRequired="False" LabelText="Age" Margin="10"/> <TextBox Grid.Row="1" Grid.Column="1" Margin="10 5"></TextBox> <Button Grid.Row="2" Grid.Column="1" Height="20" Width="100" Content="Submit"></Button> </Grid> </Window>

Now Run Project and lest have see the amazing output.

Dependency properties example output

Please feel free for any suggestion and please comment your valuable feedback.

Thank you.

;



share post :

Popular Posts

How to Create WCF service and host in Windows Service in WCF Service / Jan 13, 2017
Dependency properties in WPF in WPF / Oct 01, 2018
Static constructor in CSharp(C#.Net) in C#.Net / Feb 11, 2017
How to use tuples with more new feature in C# 7.0 in C#.Net / Jan 20, 2017
Method Overloading in C# in C#.Net / Feb 07, 2017
Interface in c# with example in C#.Net / May 14, 2017

Say Hi It’s Free!

  • Ghaziabad Uttar Pradesh India

  • avnish@ymail.com

  • (+91)-847-107-5432

Success/Error Message Goes Here

Avnish Kumar

.Net Developer

Download Resume
Drink A Coffee With Me Today