wpf - 如何使 Binding 尊重 DependencyProperty 值强制?

标签 wpf binding dependency-properties coercion

我有一个带有 DependencyProperty 和 CoerceValueCallback 的控件。 此属性绑定(bind)到模型对象上的属性。

当将控件属性设置为导致强制的值时,绑定(bind)会将非强制值推送到模型对象。控件上的属性值已正确强制。

如何获得 Binding 将强制值推送到模型对象?

void Initialize()
{
    UIObject ui = new UIObject();
    ModelObject m = new ModelObject();
    m.P = 4;

    Binding b = new Binding("P");
    b.Source = m;
    b.Mode = BindingMode.TwoWay;
    Debug.WriteLine("SetBinding");
    // setting the binding will push the model value to the UI
    ui.SetBinding(UIObject.PProperty, b);

    // Setting the UI value will result in coercion but only in the UI.
    // The value pushed to the model through the binding is not coerced.
    Debug.WriteLine("Set to -4");
    ui.P = -4;

    Debug.Assert(ui.P == 0);
    // The binding is TwoWay, the DP value is coerced to 0.
    Debug.Assert(m.P == 0); // Not true. This will be -4. Why???
}

class UIObject : FrameworkElement
{
    public static readonly DependencyProperty PProperty =
        DependencyProperty.Register("P", typeof(int), typeof(UIObject), 
        new FrameworkPropertyMetadata(
            new PropertyChangedCallback(OnPChanged), 
            new CoerceValueCallback(CoerceP)));

    public int P
    {
        get { return (int)GetValue(PProperty); }
        set { SetValue(PProperty, value); }
    }

    private static void OnPChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        Debug.WriteLine(typeof(UIObject) + ".P changed from " + e.OldValue + " to " + e.NewValue);
    }

    private static object CoerceP(DependencyObject sender, object value)
    {
        int p = (int)value;
        if (p < 0)
        {
            Debug.WriteLine(typeof(UIObject) + ".P coerced from " + p + " to 0");
            p = 0;
        }
        return p;
    }
}

class ModelObject
{
    private int p;
    public int P
    {
        get
        {
            Debug.WriteLine(this + ".P returned " + this.p);
            return this.p;
        }
        set
        {
            Debug.WriteLine(this + ".P changed from +" + this.p + " to " + value);
            this.p = value;
        }
    }
}

最佳答案

我认为这就是强制的整个想法 - 即时正确的值而不触发任何其他依赖项的修改。您可以使用下面的代码代替 native 强制机制:

OnPChanged(/* ... */)
{
    // ...
    var coercedP = CoerceP(P);
    if (P != coercedP)
        P = coercedP;
    // ...
}

HTH。

关于wpf - 如何使 Binding 尊重 DependencyProperty 值强制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/516210/

相关文章:

javascript - 在 mustache Polymer 2.0 中绑定(bind)对象

c# - 父对象的 WPF 中的数据绑定(bind)

wpf - 依赖属性的 PropertyChangedCallback 没有被调用

c# - 如何将 Nullable 依赖属性设置为 Null?

c# - ListBoxItem 动画和不透明度

wpf - 当 Expander 展开时滚动 ScrollViewer

.net - XAML:为什么这个触发器不起作用?

wpf - 在 WPF 中,如何在右键单击时选择光标下的 TreeView 项?

wpf - 在 DataTemplates 中使用 TemplateBinding

.net - 如何创建自定义 *write-only* 依赖属性?