5

我的主窗口中有一个StatusBar,我的主窗口中也有一个副本UserControl。从我的事件处理程序中UserControl,我想StatusBar在主窗口中更新。这样做的最佳方法是什么?有没有办法从事件处理程序中object senderRoutedEventArgs e在事件处理程序中访问我的主窗口实例UserControl

编辑: 感谢卢卡斯的回答本教程,我想出了以下解决方案:

添加到我的UserControl

public delegate void UpdateStatusBarEventHandler(string message);

public event UpdateStatusBarEventHandler UpdateStatusBar;

添加到我的主窗口的构造函数中,之后InitializeComponent

uct_requiredFields.UpdateStatusBar += updateStatusBar;

我将此方法添加到我的主窗口:

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

然后,在 myUserControl中,我可以执行以下操作来更新状态栏:

if (null != UpdateStatusBar)
{
    UpdateStatusBar("woot, message");
}
4

1 回答 1

5

我会通过我自己的委托或定义向 UserControl 添加一个事件

public event UpdateStatusBar UpdateBar;

然后通过在 UserControl (或您使用的其他东西)中单击按钮来提升它

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

我假设你在 contructor 的主窗口中有一个 UserControl 的实例

 myUserControl.UpdateBar += MyMethodWhichUpdatesStatusBar();
于 2010-08-11T16:51:18.673 回答