DependencyObject.InvalidateProperty 不起作用 [英] DependencyObject.InvalidateProperty not working

查看:19
本文介绍了DependencyObject.InvalidateProperty 不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于 MSDN 上的文档...

Based on the documentation via MSDN...

您还可以使用 InvalidateProperty 来强制重新评估绑定针对不能的数据源实施建议的INotifyPropertyChanged 通知机制...

You can also use InvalidateProperty to force re-evaluation of a binding against a data source that is not able to implement the recommended INotifyPropertyChanged notification mechanism...

...下面的代码应该可以工作,但没有.

...the code below should work, yet it doesn't.

public partial class Window1 : Window
{
    private Payload _payload = new Payload();

    public Window1()
    {
        InitializeComponent();

        this.DataContext = _payload;
    }

    private void Invalidate(object sender, RoutedEventArgs e)
    {
        _payload.Timestamp = DateTime.Now.Add(TimeSpan.FromHours(1)).ToLongTimeString();

        Button b = sender as Button;
        b.InvalidateProperty(Button.ContentProperty);
    }
}

public class Payload
{
    private String _payload = DateTime.Now.ToLongTimeString();
    public String Timestamp 
    {
        get
        {
            return _payload;
        }
        set
        {
            _payload = value;
        }
   }
}

<Grid>
    <Button Click="Invalidate"
            Width="100" 
            Height="50" 
            Content="{Binding Path=Timestamp}"/>
</Grid>

知道是什么导致了这种行为吗?

Any idea what is causing this behavior?

推荐答案

正如你所提到的,它应该有效,但没有.但有一个简单的解决方法:

As you mentioned, it ought to work but doesn't. But there is a simple workaround:

// Doesn't work:
//b.InvalidateProperty(Button.ContentProperty);

// Works:
BindingOperations.GetBindingExpression(b, Button.ContentProperty).UpdateTarget();

我调试到参考源中,并且所有 InvalidateProperty 在您的情况下所做的都是导致缓存值从 BindingExpression 重新读取到 Button Content 属性.顺便说一句,我不知道这在什么时候甚至是必要的,但让 BindingExpression 重新读取原始属性并没有用.

I debugged into the reference source and all InvalidateProperty does in your situation is cause a cached value to be re-read from the BindingExpression into the Button Content property. Offhand, I don't know when this would even be necessary but it's not useful to get the BindingExpression to re-read the raw property.

由于该解决方法既方便又通用,唯一需要进一步努力的是向 Microsoft 提交错误报告.

Since the workaround is convenient and general, the only further effort warranted is filing a bug report with Microsoft.

这篇关于DependencyObject.InvalidateProperty 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆