0

I have a C# custom WPF control. I have properties on the control that are based on DependencyProperty's.

public static readonly DependencyProperty CurrentStateProperty = 
 DependencyProperty.Register( "CurrentState", typeof(ControlStateEnum),
 typeof(MyCustomControl), new PropertyMetadata(ControlStateEnum.Started));

public ControlStateEnum CurrentState
{
    get { return (ControlStateEnum) GetValue(CurrentStateProperty); }
    set { SetValue(CurrentStateProperty, value); }
}

Now, if I use the control, and try to use it, ala:

<myControls:MyCustomControl CurrentState="Loaded" />

The CurrentState never gets set to "Loaded" and remains "Started". I want to make it capable of binding, but also capable of being set without binding... Is there something I don't understand or am missing?

When I set a breakpoint on the setter, it doesn't update on the window load.

Locke
  • 1,133
  • 11
  • 32
  • 2
    possible duplicate of [Setters not run on Dependency Properties?](http://stackoverflow.com/questions/4225373/setters-not-run-on-dependency-properties) – parapura rajkumar Jul 20 '12 at 19:50
  • So, in the end the value was being set on the control from the XAML after the control had been initialized and loaded. So the way to handle it was to add a PropertyChangedHandler on the DependencyProperty. Thanks for the help in diagnosing it, parapura. – Locke Jul 20 '12 at 20:32

2 Answers2

1

Are you sure your not changed the enum somewhere else after the controls get loaded, because that should work as intended

MyKuLLSKI
  • 5,285
  • 3
  • 20
  • 39
  • Unfortunately, it does not appear that the setter is firing at all. – Locke Jul 20 '12 at 20:24
  • 1
    Its not going to...Not on initialization – MyKuLLSKI Jul 20 '12 at 20:32
  • The value does get changed and updated. Unfortunately, this happens AFTER the control is loaded and constructed. And as the other link suggests, the Setters/Getters are called via Get/SetValue, and we don't see it change. Therefore, the only way to handle changes and catch them in the XAML is by having a callback. – Locke Jul 20 '12 at 20:37
  • After every sentence I said yes. I dont see the problem here – MyKuLLSKI Jul 20 '12 at 21:01
  • 1
    When you write `new PropertyMetadata(ControlStateEnum.Started))` that means the default value is started no matter when you do when constructing the control. Then this `CurrentState="Loaded"` overrides it. This is how ALL WPF controls work – MyKuLLSKI Jul 20 '12 at 21:06
0

So, in the end the value was being set on the control from the XAML after the control had been initialized and loaded. So the way to handle it was to add a PropertyChangedHandler on the DependencyProperty.

parapura had a link to the right answer (http://stackoverflow.com/questions/4225373/setters-not-run-on-dependency-properties).

Locke
  • 1,133
  • 11
  • 32