-1

Ok so I have a test control that derives from Panel. I added new dependency property to it.

public class TestPanel : Panel
{
    public static DependencyProperty TestProperty = DependencyProperty.Register(
        "Test",
        typeof(double),
        typeof(TestPanel),
        new FrameworkPropertyMetadata(
            0.0,
            null));

    public double Test
    {
        get
        {
            return (double)this.GetValue(TestProperty);

        }
        set
        {
            this.SetValue(TestProperty, value);
        }
    }
}

I then defined it in xaml <controls:TestPanel Test="50" />

But now I wonder, why the setter of Test is not called? Shouldn't it pass value(50)? I get default value (0.0) during arrange pass.

Or is it only valid using the binding instead?

benderto
  • 896
  • 11
  • 39
  • The WPF calls SetValue directly. So your setter will not be executed. But the Test value should be 50 after control initialization. Do you read this value anywhere? – Yevgeniy May 17 '17 at 14:56
  • Yeah, I had mismatch in dependecy properties, duplicate also point me to extended information, thank you – benderto May 17 '17 at 14:58

1 Answers1

3

The XAML processor sets the value of the dependency property using the SetValue method:

Setters not run on Dependency Properties?

If you want to do something whenever the property is being set to a new value, you should register a callback:

public static DependencyProperty TestProperty = DependencyProperty.Register(
"Test",
typeof(double),
typeof(TestPanel),
new FrameworkPropertyMetadata(
   0.0,
   OnPropertyChanged));

private static object OnPropertyChanged(DependencyObject d, object baseValue)
{
    //...
}
Community
  • 1
  • 1
mm8
  • 163,881
  • 10
  • 57
  • 88
  • 2
    Who downvoted this? this describes exactly what is wrong and how to mediate it – Timothy Groote May 17 '17 at 14:55
  • 2
    Not mine downvote, but there are plenty of duplicates, is the answer really needed? E.g. [here](http://stackoverflow.com/q/9212583/1997232) is another one. – Sinatr May 17 '17 at 14:55