【问题标题】:Dependency Property Coercion binding issues依赖属性强制绑定问题
【发布时间】:2011-03-01 12:28:12
【问题描述】:

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

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

<TextBox x:Name="textbox" Text="{Binding Path=MyProperty,Mode=TwoWay}"></TextBox>

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";
}

当我在文本框中输入随机字符串并点击选项卡时,我希望 textbox.Text 被重置为“强制值”。如果我调试,我会看到应用在强制功能中中断,但 UI 没有更新。

有趣的是,同样的代码在 VS2010 中也可以使用,UI 会使用强制值进行更新。 有人知道发生了什么吗?

这是一个 WPF 错误吗?还是我错过了什么?

【问题讨论】:

    标签: c# xaml data-binding coercion


    【解决方案1】:

    【讨论】:

    • 那行得通,但是如果强制只能发生在按钮单击或其他东西上,那有什么意义......我不妨手动更新值。有趣的是VS2010/.net4.0可以自动做到。所以看起来 .net3.5SP1 没有完全烘焙强制转换。
    • 我猜有太多人抱怨 Coerce 没有按预期工作。
    • 我现在已经多次找到该解决方案的提示,但没有一个解释 where 以插入对UpdateTarget() 的调用。在CoerceValueCallback?这当然为时过早,因为到那时价值还没有被强制。那么 - 什么时候应该调用UpdateTarget()? (我在related question 中进行了更广泛的阐述。)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多