Before I start to explain my problem: The Slider is just an example for the following problem. I work on a custom control, that has to do a very similar thing like the slider does here:
Scenario:
- I have bound a
Slider.Valueto my ViewModel property calledMyValue. - I have defined the
Maximumof theSliderto be100. - Now I set the Property
MyValueto200.
What is the problem?
- The Slider will internally coerce the value to be 100.
- But the property
MyPropertyisn't being updated. - In my case (the custom control I built), I need to continue with the coersed value (100) later on, NOT the old (200) value.
Question:
Is there anything I can do in my custom control?
For example I tried myControl.GetExpression(MyValueProperty).UpdateSource(); in both my CoerseValueCallback and PropertyChangedCallback, but no matter what I try, the setter of the bound ViewModel-property is NEVER called and the property stays out of sync.
Bind the
Maximumproperty of yourSliderto another view model property and implement logic to ensure that your values are always within the valid range in your view model class.The control rightfully coerces the values but the logic of synchronizing them should be implemented in the view model class.
Your custom control should be able to simply set the source property of its current
DataContextwhenever the value is coerced though.this.GetBindingExpression(Slider.ValueProperty).ResolvedSourcePropertyNameshould give you the name of the source property and then you can for example set it using reflection if callingUpdateSource()on theBindingExpressiondoesn't work.