Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF, updating status bar in main window from within UserControl

I have a StatusBar in my main window, and I also have a copy of a UserControl in my main window. From within event handlers in my UserControl, I want to update the StatusBar in the main window. What would be the best way of doing this? Is there a way of getting access to the instance of my main window from object sender or RoutedEventArgs e in an event handler in UserControl?

Edit: thanks to lukas's answer and this tutorial, I came up with the following solution:

Added to my UserControl:

public delegate void UpdateStatusBarEventHandler(string message);

public event UpdateStatusBarEventHandler UpdateStatusBar;

Added to my main window's constructor, after InitializeComponent:

uct_requiredFields.UpdateStatusBar += updateStatusBar;

And I added this method to my main window:

private void updateStatusBar(string message)
{
    sti_mainStatus.Content = message;
}

Then, from within my UserControl, I can do the following to update the status bar:

if (null != UpdateStatusBar)
{
    UpdateStatusBar("woot, message");
}
like image 446
Sarah Vessels Avatar asked Aug 11 '10 16:08

Sarah Vessels


1 Answers

I would add an event to UserControl via my own delegate or defined

public event UpdateStatusBar UpdateBar;

and then rise it via button click in UserControl ( or other thing that u use)

    private void UserContolButton_Click(object sender, RoutedEventArgs e)
    {
        if(UpdateBar != null)
          UpdateBar(); // send here the message
    }

I assume u have an instance of UserControl in the main window in contructor

 myUserControl.UpdateBar += MyMethodWhichUpdatesStatusBar();
like image 88
Lukasz Madon Avatar answered Sep 23 '22 23:09

Lukasz Madon