Setters not run on Dependency Properties?

17,249

Solution 1

The WPF binding engine calls GetValue and SetValue directly (bypassing the property setters and getters). You need the property to be there so it can be supported in the XAML markup (and compile correctly).

Solution 2

To create a DependencyProperty, add a static field of type DepdencyProperty to your type and call DependencyProperty.Register() to create an instance of a dependency property. The name of the DependendyProperty must always end with ...Property. This is a naming convention in WPF.

To make it accessable as a normal .NET property you need to add a property wrapper. This wrapper does nothing else than internally getting and setting the value by using the GetValue() and SetValue() Methods inherited from DependencyObject and passing the DependencyProperty as key.

Do not add any logic to these properties, because they are only called when you set the property from code. If you set the property from XAML the SetValue() method is called directly.

Each DependencyProperty provides callbacks for change notification, value coercion and validation. These callbacks are registered on the dependency property.

source: http://www.wpftutorial.net/DependencyProperties.html

Share:
17,249
Jiew Meng
Author by

Jiew Meng

Web Developer & Computer Science Student Tools of Trade: PHP, Symfony MVC, Doctrine ORM, HTML, CSS, jQuery/JS Looking at Python/Google App Engine, C#/WPF/Entity Framework I hope to develop usable web applications like Wunderlist, SpringPad in the future

Updated on June 03, 2022

Comments

  • Jiew Meng
    Jiew Meng about 2 years

    Just a short question, to clarify some doubts. Are setters not run when an element is bound to a dependency property?

    public string TextContent
    {
        get { return (string)GetValue(TextContentProperty); }
        set { SetValue(TextContentProperty, value); Debug.WriteLine("Setting value of TextContent: " + value); }
    }
    
    public static readonly DependencyProperty TextContentProperty =
        DependencyProperty.Register("TextContent", typeof(string), typeof(MarkdownEditor), new UIPropertyMetadata(""));
    

    ...

    <TextBox Text="{Binding TextContent}" />
    

    As I noticed the below in my setter does not run

    Debug.WriteLine("Setting value of TextContent: " + value);
    
  • Emixam23
    Emixam23 almost 8 years
    Hi, I'm not sure to understand what you say?
  • Dave
    Dave over 7 years
    @Emixam23 Dean is saying that the OP cannot put a debug statement in the TextContent property to determine whether or not the DP is being bound properly, because WPF will call SetValue, not the TextContent setter.
  • j00hi
    j00hi about 7 years
    you have saved my life!