Dummy01
Dummy01

Reputation: 1995

Dependency Property Default Value

I am new with WPF and dependency properties and my question might be totally 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 to have the code in the OnIsEditablePropertyChanged to be executed also for the default value of my property, which doesn't happen.

What am I doing wrong, or how should I do this in your opiniion?

Thank you in advance.

Upvotes: 4

Views: 3670

Answers (3)

Vicro
Vicro

Reputation: 575

Instead of changing the visibility in code, you should Bind the Visibility property in XAML and use a boolean to Visibility Converter.

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

Upvotes: 3

dain
dain

Reputation: 6699

I think a much better approach would be to set up stackPanelButtons.Visibility = Visibility.Collapsed in your XAML as default too, in which case you don't need to run all this code on startup!

Upvotes: 0

Eilistraee
Eilistraee

Reputation: 8290

The OnPropertyChanged callback won't be called on startup: The "default" value is in fact never really "set". Default: The value of the property when it isn't set.

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

Avoid duplicating this code in the constructor and in the property changed callback: Put it in a common method called by both ie:

void OnIsEditableChangedImpl(bool newValue)
{
   ....
}

Upvotes: 2

Related Questions