Mhazad's Blog

December 13, 2010

WPF property compatible with XAML binding and Code behind binding.

Filed under: C#, Dependency Property, WPF, XAML — Mahmudul Haque Azad @ 7:33 am

WPF and dependency property are indispensable part. Without dependency property and MVVM you are almost no where in WPF development. But improper use of dependency property can create night mare.

Let’s take the following example.

Suppose we have created a custom media player control and we want to bind the Source property from XAML. It is to be noted that once the source property is set we need to do some additional related thing.

Here is the initial code snippet of Source Dependency Property

And here is our XAML

Now if we run our application we shall see that none of the code written after

SetValue(SourceProperty, value);

Will execute.

The reason behind this is If we set the property from XAML the SetValue() method is called directly. So our player will not work if we bind the source property from XAML!

We can easily overcome this problem if we use the following overloaded version of DependencyProperty.Register method.

As you can see that the new FrameworkPropertyMetaData is nothing but a method which is fired once the Source property is changed irrespective whether it is changed from XAML or code behind. Since we are setting the Source property in OnMediaSourceChanged method so now the Set method of source will execute with all business logic! Seems our problem is solved!!

But the fact is it is not solved yet rather it gives birth of another problem. If we set the Source property from the code behind, the Set property of Source along with related code written in Set method will executedtwice, one for setting it from code behind and another from OnMediaSourceChanged method.

The solution of this problem is, keep the Set property free from any business logic (or any code!). Rather whatever code is needed to execute, keep those in some separate method and call that method from OnMediaSourceChanged.

Here comes the code that is fully compatible with XAML binding and code behind.

Blog at