从子页面访问父窗口 UI

本文关键字:窗口 UI 访问 | 更新日期: 2023-09-27 18:35:45

我有一个Page加载在Window中。当用户登录时,我想在Window中显示一个Image,但是登录方法在Page内。我正在尝试在Window内调用一个方法,该方法用于显示MessageBox但不显示Image。这是一些代码;

主窗口

public void initUI()
{
    navigationFrame.Navigate(new Uri("View/MainPages/LoginPage.xaml", UriKind.Relative));
}
public void ShowSDCImage()
{
    sdcLogo.Visibility = Visibility.Visible;
    MessageBox.Show("Test"); // This is displayed
}

子页面

private void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        if (UserAuthenticationService.AuthenticateUser(passwordBox.Password))
        {
            var lGs = new LoginService();
            var sqlServerCheck = new MySQLServerCheck();
            if (sqlServerCheck.ServerIsOnline())
            {
                MainWindow mw = new MainWindow();
                mw.ShowSDCImage();                    
                NavigationService.Navigate(new Uri("View/MainPages/DashboardPage.xaml", UriKind.Relative));
            }
            else
            {
                MessageBox.Show("Sorry, the server is offline. Please notify IT.");
            }
        }
        else
        {
            MessageBox.Show("Incorrect Password");
        }
        e.Handled = true;
    }
    if (e.Key == Key.Escape)
    {
        Application.Current.Shutdown();
    }
}

正如您在主窗口中看到的,我正在尝试使用

MainWindow mw = new MainWindow(); mw.ShowSDCImage();

虽然这会显示MessageBox,但它不显示Image。我做错了什么,如何成功访问主窗口的Image

从子页面访问父窗口 UI

public static MainWindow W;
private void EnterPressed(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        if (UserAuthenticationService.AuthenticateUser(passwordBox.Password))
        {
            var lGs = new LoginService();
            var sqlServerCheck = new MySQLServerCheck();
            if (sqlServerCheck.ServerIsOnline())
            {
                W.ShowSDCImage();                    
                NavigationService.Navigate(new Uri("View/MainPages/DashboardPage.xaml", UriKind.Relative));
            }
            else
            {
                MessageBox.Show("Sorry, the server is offline. Please notify IT.");
            }
        }
        else
        {
            MessageBox.Show("Incorrect Password");
        }
        e.Handled = true;
    }
    if (e.Key == Key.Escape)
    {
        Application.Current.Shutdown();
    }
}

用:

// Call this in your MainWindow() code:
public MainWindow()
{
    yourClassHere.W = this;
}