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

发布于 2024-09-13 12:24:31 字数 1230 浏览 5 评论 0原文

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

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

添加到我的 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");
}

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");
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

辞旧 2024-09-20 12:24:31

我将通过我自己的委托或定义向 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();

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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文