WPF,如何从UserControl更新主窗口中的状态栏

5
我在我的主窗口中有一个 StatusBar,并且我也在我的主窗口中复制了一个 UserControl。从我的 UserControl 的事件处理程序中,我想要更新主窗口中的 StatusBar。最好的方法是什么?是否有一种方法可以在 UserControl 中的事件处理程序中从 object sender 或 RoutedEventArgs e 获取我的主窗口实例?
编辑:感谢 lukas 的答案和这个教程,我得到了以下解决方案:
添加到我的 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;
}

然后,从我的 UserControl 内部,我可以执行以下操作来更新状态栏:
if (null != UpdateStatusBar)
{
    UpdateStatusBar("woot, message");
}
1个回答

5
我会通过自己的委托或定义,向UserControl添加事件。
public event UpdateStatusBar UpdateBar;

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

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

我假设您在主窗口中有一个UserControl实例 在构造函数中。
 myUserControl.UpdateBar += MyMethodWhichUpdatesStatusBar();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接