【发布时间】:2020-04-21 00:51:51
【问题描述】:
我有以下自定义控件:
<abc:MyControl MyProperty="{Binding FieldInMyModel, Mode=TwoWay}">
在我的自定义控件中,我有
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;
}
}
}
在我的模型中,我将FieldInMyModel 的值更改为对我的范围无效。 OnMyPropertyChanged 被调用,并且在从收到的无效值中生成有效值后,我希望 FieldInMyModel 将更新为具有 MyProperty 的新值,但实际上没有任何反应。有什么想法吗?
【问题讨论】:
-
您考虑过使用CoerceValueCallback吗?
-
您是否希望在视图模型当前正在更新其 FieldInMyModel 属性时将经过验证的(即新的属性值)传递回视图模型?
-
@Clemens 是的,这正是我想要的。顺便说一句,coerceValueCallback 也不起作用。
-
Afaik 这将不起作用,因为该框架并非旨在将值传递回绑定源,而该源当前正在更改。您可以尝试以某种方式异步执行此操作。
-
是的,这也是我同时想到和害怕的:)。将尝试通过引入新属性来解决问题,并在模型中进行验证,然后再将其传递给我的控件。谢谢!
标签: wpf two-way-binding