7

For a DependencyProperty, I set a value using DependencyObject.SetCurrentValue(property, value). How does one unset the value so that the property evaluates to the normal local value again?

Palec
  • 12,743
  • 8
  • 69
  • 138
Kevin Hsu
  • 1,726
  • 11
  • 14

2 Answers2

17

Calling InvalidateProperty will force the value to be reevaluated, and it appears to ignore the "current" value, so it effectively will unset it.

Johan Larsson
  • 17,112
  • 9
  • 74
  • 88
nmclean
  • 7,564
  • 2
  • 28
  • 37
  • 3
    +1 This is by far a better solution, since it appears that WPF already keeps track of what the previous value was, even if it is not databound. – reSPAWNed Aug 29 '13 at 09:03
  • InvalidateProperty reverts value back only when no binding is assigned. When it is - current value isn't "temporary" anymore because it immediately goes to binding source. And now the binding source provides new value. Therefore, when InvalidateProperty is being called it gets updated binding source. – white.zaz Jun 30 '16 at 12:53
  • @white.zaz Not true when using [SetCurrentValue](https://msdn.microsoft.com/en-us/library/system.windows.dependencyobject.setcurrentvalue(v=vs.110).aspx). Note this is different from the regular [SetValue](https://msdn.microsoft.com/en-us/library/ms597473(v=vs.110).aspx) that is called on property assignment. `SetCurrentValue` will not update the binding source. – nmclean Jun 30 '16 at 15:33
  • @nmclean SetCurrentValue does update binding source. I created small example for you https://www.dropbox.com/s/olotsz8muzdfrl4/SetCurrentValueTest.zip?dl=0 – white.zaz Jun 30 '16 at 20:31
  • From MSDN: "SetCurrentValue - sets the value of a dependency property without changing its value source." I believe you misunderstood the difference between 'binding source' and 'value source'. – white.zaz Jun 30 '16 at 20:40
  • @white.zaz I see what you're saying. In your original comment you should have said "only when there is no source update". The reason it doesn't revert in your example is *not* because there is a binding assigned, but specifically because it is a `TwoWay` binding which updates source on every target property change. The revert will work with all source-to-target bindings however. – nmclean Jul 05 '16 at 18:34
-2

I don't believe you can 'unset' the value; you simply 'reset' the value to the previously saved value. If you dont have that, then you're OOL... -- Tejs

I do not think there is a way to do that, either. This method changes the value rather than adding an override in the ladder of precedences. Just get the value and store it somewhere before you overwrite it.

Community
  • 1
  • 1
H.B.
  • 166,899
  • 29
  • 327
  • 400