0
votes

I have the following custom control:

<abc:MyControl MyProperty="{Binding FieldInMyModel, Mode=TwoWay}">

And in my custom control I have

public static readonly DependencyProperty MyPropertyProperty =
     DependencyProperty.Register("MyProperty", typeof(double), typeof(MyControl),
     new PropertyMetadata(0.0, OnMyPropertyChanged));

public double MyProperty
{
     get { return (double)GetValue(MyPropertyProperty ); }
     set { SetValue(MyPropertyProperty , value); }
}

private static void OnMyPropertyChanged(DependencyObject d, 
     DependencyPropertyChangedEventArgs e)
{
     if (d is MyControl mc)
     {
          // here I check if the new value is valid for my scope.
          // if it is not I update it here to be valid
          var v = (double)e.NewValue;
          if (!mc.IsValidValue(v))
          {
               v = mc.MakeValidValue(v);
               mc.MyProperty = v;
          }
     }
}

In my model I change the value of FieldInMyModel to be not valid for my scope. OnMyPropertyChanged is called, and after making a valid value from received invalid value I expect that the FieldInMyModel will be updated to have the new value of MyProperty but actually nothing happens. Any thought?

1
Have you considered using a CoerceValueCallback? - Clemens
Do you expect the validated, i.e. new property value to be passed back to the view model while the view model is currently updating its FieldInMyModel property? - Clemens
@Clemens yes, that is exactly what I want. btw, coerceValueCallback also didn't work for it. - L_A_Hooper
Afaik this will not work, because the framework is not designed to pass a value back to a binding source while this source is currently changing. You may try to do this asynchronously somehow. - Clemens
Yea, this was what I also was thinking of and afraid of at the same time :) . Will try to workaround by introducing a new property instead and do the validation in the model before passing it to my control. Thanks! - L_A_Hooper

1 Answers

-1
votes

Setting MyProperty from code will break your TwoWay Binding.

Instead you can use SetCurrentValue method.