Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DependencyObject.InvalidateProperty not working

Tags:

c#

binding

wpf

Based on the documentation via MSDN...

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?

like image 486
Aaron McIver Avatar asked Feb 07 '11 21:02

Aaron McIver


1 Answers

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();

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.

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

like image 78
Rick Sladkey Avatar answered Sep 22 '22 05:09

Rick Sladkey