Default Property Value

I am new to WPF and dependency properties, and my question might be a complete newbie ...

I have the following dependency property:

public static readonly DependencyProperty IsEditableProperty = DependencyProperty.Register("IsEditable", typeof(bool), typeof(EditContactUserControl), new FrameworkPropertyMetadata(false, OnIsEditablePropertyChanged)); public bool IsEditable { get { return (bool)GetValue(IsEditableProperty); } set { SetValue(IsEditableProperty, value); } } private static void OnIsEditablePropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e) { EditContactUserControl control = source as EditContactUserControl; bool isEditable = (bool)e.NewValue; if (isEditable) control.stackPanelButtons.Visibility = Visibility.Visible; else control.stackPanelButtons.Visibility = Visibility.Collapsed; } 

The problem is that I want the code in OnIsEditablePropertyChanged executed also for the default value for my property, which is not happening.

What am I doing wrong, or how should I do it in my opinion?

Thanks in advance.

+4
source share
3 answers

Instead of changing the visibility in the code, you should Bind the Visibility property in XAML and use a boolean value for the visibility converter.

If you do this, it doesn't matter if the property is initialized or not.

+3
source

The OnPropertyChanged callback will not be called at startup: the default value is never actually set. Default value: the value of the property, if not set.

If you want to execute some code when starting control, put it in the override of the ApplyTemplate method (in the case of TemplatedControl) or at the end of your constructor (in the case of UserControl)

Avoid duplicating this code in the constructor and in the modified property callback: put it in a generic method called as:

 void OnIsEditableChangedImpl(bool newValue) { .... } 
+2
source

I think a much better approach would be to set stackPanelButtons.Visibility = Visibility.Collapsed in your XAML by default, in which case you do not need to run all this code at startup!

0
source

All Articles