Jack
Jack

Reputation: 9242

Best way to update UI from other classes?

I've got several nested classes, with the following structure:

BackupLocation contains list of BackupClients

BackupClients contains a list of BackupVersions

BackupVersions contains a list of BackupFiles

In my UI - Im populating a combo box with BackupLocations - and have several listboxes for the clients, versions, and files.

When processing the BackupLocations - I can update my status bar easily because thats the top level class that the UI creates. But how can I update the status bar and progress bar on each file being processed? Since the BackupFiles are 3 levels deep, I cant see any way to update the UI. The actual processing of the files are within the BackupVersion class - which loads its files.

I think it probably has something to do with events and delegates - but am unsure exactly how to proceed with this, any help would be appreciated.

Upvotes: 1

Views: 1078

Answers (1)

Kyle Rosendo
Kyle Rosendo

Reputation: 25277

I would use events and bubble them up through the classes.

Basically:

  • Create an event in each class with event args that can handle the specific status update that you wish to show.
  • When its time to push an update, call the event
  • Handle the event from the class above it, adding in any identifying information you want to to the Event args (E.g.: if you want to use 2 or 3 status bars, identify which status bar it would need to update - or rather the level at which the update took place)
  • Invoke the event on to the class using the new event args, and so on, so forth.

In a very simplistic example of code, see the below (no null checking etc. just the general concept):

class A
{
    public A()
    {
        ExampleB.StatusUpdate += new EventHandler<ExampleArgs>(ExampleB_StatusUpdate);
    }

    void ExampleB_StatusUpdate(object sender, ExampleArgs e)
    {
        UpdateUI();
    }

    public B ExampleB { get; set; }

    public event EventHandler<ExampleArgs> StatusUpdate;

    protected virtual void OnChanged(ExampleArgs e)
    {
        if (StatusUpdate != null)
        {
            StatusUpdate(this, e);
        }
    }
}

class B
{
    public B()
    {
        ExampleC.StatusUpdate += new EventHandler<ExampleArgs>(ExampleC_StatusUpdate);
    }

    void ExampleC_StatusUpdate(object sender, ExampleArgs e)
    {
        OnChanged(e);
    }

    public C ExampleC { get; set; }

    public event EventHandler<ExampleArgs> StatusUpdate;

    protected virtual void OnChanged(ExampleArgs e)
    {
        if (StatusUpdate != null)
        {
            StatusUpdate(this, e);
        }
    }
}

class C
{
    public event EventHandler<ExampleArgs> StatusUpdate;

    protected virtual void OnChanged(ExampleArgs e)
    {
        if (StatusUpdate != null)
        {
            StatusUpdate(this, e);
        }
    }
}

class ExampleArgs : EventArgs
{
    public string StatusUpdate { get; set; }
}

Upvotes: 4

Related Questions