gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:28:27 26 4
gpt4 key购买 nike

我有一个带有 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com