Friday, December 6, 2013

Boolean dependency property and its default value.

What’s up community, today I going to share a very basic trick that I learned while working on a wizard control. I would rather say that is a convention that i didn’t know previously. probably all the the WPF developer knows it, but just in case anyone needed it and wondering why its not working.

Enough talk, lets get in to the business, so i was developing a custom control, precisely a reusable wpf wizard control. And I introduced a dependency property for two mode of the UI here is how it looks.

public bool ShouldIgnoreStep
{
get { return (bool)GetValue(ShouldIgnoreStepProperty); }
set { SetValue(ShouldIgnoreStepProperty, value); }
}

public static readonly DependencyProperty ShouldIgnoreStepProperty =
DependencyProperty.Register(
"ShouldIgnoreStep", typeof(bool), typeof(RiteqWizardPage),
new PropertyMetadata(false, OnPropertyChanged));

private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RiteqWizardPage riteqWizardPage
= d as RiteqWizardPage;
if (e.Property.Name.Equals("ShouldIgnoreStep"))
{
if (e.NewValue != e.OldValue)
{
if (riteqWizardPage != null)
{
riteqWizardPage.OnShouldIgnoreStepChanged();
}
}
}
}


I started to use the property and set the properties value in codes. The first one that i used in the same container worked okay. But the subsequent controls in the same container was not getting property set as I have dependent code when the dependency property is changed I wish to do some work. But the OnPropertyChanged event on the other instance of the control returning always the default value.


I was about the pull all my hairs out, but suddenly it strikes in my head, the problem is the default value that I set to the dependency property.


Then I tried with default value to “null”, and it worked!. Wallah!. Well offcourse I had to use nullable bool to be able to set its default value to null.


In my opinion you should always use default property as to null unless you have some condition that requires to set default value.


public bool? ShouldIgnoreStep
{
get { return (bool?)GetValue(ShouldIgnoreStepProperty); }
set { SetValue(ShouldIgnoreStepProperty, value); }
}

public static readonly DependencyProperty ShouldIgnoreStepProperty =
DependencyProperty.Register(
"ShouldIgnoreStep", typeof(bool?), typeof(RiteqWizardPage),
new PropertyMetadata(null, OnPropertyChanged));

private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
RiteqWizardPage riteqWizardPage
= d as RiteqWizardPage;
if (e.Property.Name.Equals("ShouldIgnoreStep"))
{
if (e.NewValue != e.OldValue)
{
if (riteqWizardPage != null)
{
riteqWizardPage.OnShouldIgnoreStepChanged();
}
}
}
}

Cheers! and happy coding.