依赖属性强制绑定问题

Nit*_*ari 8 c# data-binding xaml coercion

我安装了VS2008和VS2010,我看到了一个非常奇怪的行为

在VS2008中,我有一个简单的WPF应用程序:

<TextBox x:Name="textbox" Text="{Binding Path=MyProperty,Mode=TwoWay}"></TextBox>
Run Code Online (Sandbox Code Playgroud)

public Window1()
{
    InitializeComponent();
    DataContext = this;
}
public string MyProperty
{
    get { return (string)GetValue(MyPropertyProperty); }
    set { SetValue(MyPropertyProperty, value); }
}
public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyProperty", typeof(string), typeof(Window1), new PropertyMetadata("default",null,Coerce));

private static object Coerce(DependencyObject d, object baseValue)
{
    return "Coerced Value";
}
Run Code Online (Sandbox Code Playgroud)

当我在文本框中输入随机字符串并点击标签时,我希望textbox.Text重置为"Coerced Value".如果我调试我看到应用程序在Coerce功能中断,但UI没有更新.

有趣的是,这个相同的代码在VS2010中工作,UI使用Coerced值进行更新.任何人都有想法发生了什么?

它是WPF错误吗?还是我错过了什么?

Dan*_*ose 3

您必须通过 强制更新UpdateTarget()。看看http://social.msdn.microsoft.com/forums/en-US/wpf/thread/c404360c-8e31-4a85-9762-0324ed8812ef/

  • 这有效,但如果强制只能在单击按钮或其他操作时发生,那还有什么意义呢……我不妨手动更新该值。有趣的是VS2010/.net4.0可以自动做到这一点。所以看起来 .net3.5SP1 并没有完全烘焙 Coercion。 (2认同)