0

I'm trying to update a "statusbar" label during code execution to notify the user of progress.

I have the following code:

    private void FindDupsBtn_Click(object sender, RoutedEventArgs e)
    {
        var t = Stopwatch.StartNew();
        StatusLbl.Content = "Getting File Info";
        StatusLbl.Refresh();
        //StatusLbl.ChangeContent("Getting File Info");
        //code continues
    }

using the following extension methods:

public static class MyExtensions
{
    private static Action EmptyDelegate = delegate() { };

    public static void Refresh(this UIElement uiElement)
    {
        uiElement.Dispatcher.Invoke(DispatcherPriority.Background, EmptyDelegate);
    }
    public static void ChangeContent(this Label label,string content)
    {
        label.Content = content;
        label.Refresh();
    }
}

I would expect StatusLbl.Content = "" + StatusLbl.Refresh() to yield the same results as StatusLbl.ChangeContent(""). However, when I run the code with a breakpoint at the end, I get inconsistent results from ChangeContent: sometimes the label has changed and sometimes it hasn't. So far, Content + Refresh has worked every time.

Here are my questions:

  1. Why is this behavior occurring? Can I make ChangeContent be consistent?(I realize this error may be difficult to reproduce, so if you're having trouble, let me know and I'll try to help).
  2. Is there a better method for updating progress during run-time? I don't need anything sophisticated.

What I've tried: I don't have the built in Windows Forms Update method or the VB DoEvents. I have tried InvalidateVisual and attempted to set up Data Binding for StatusLbl. What I have now is an amalgam of several solutions I found online which didn't work on their own.

Edit: Later in my code I used the Content + Refresh and it didn't work. When I paused execution the code was past it and the label wasn't updated. I guess this means that I just want to know: What is the simplest way to update UI controls during code execution?

Kalev Maricq
  • 617
  • 1
  • 7
  • 24
  • Try to bind your label content to a property and try updating the property. use INotifyPropertyChanged and Disjuncture if you are updating your property form different thread. – Abin Jul 01 '15 at 18:54
  • I have marked your question as a duplicate. Please see my answer in the linked question to understand how to properly work with WPF UIs in a multi threaded scenario. If my answer does not satisfy your requirements, please feel free to create a new question. – Federico Berasategui Jul 01 '15 at 18:54
  • Also please notice that WPF is fundamentally different from winforms and the approaches used in winforms are not suitable for WPF development. – Federico Berasategui Jul 01 '15 at 18:55

0 Answers0