从子页面访问父窗口UI

时间:2016-02-23 11:09:45

标签: c# wpf xaml window

我在Page内加载了Window。当用户登录时,我想在Image中显示Window,但登录方法位于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
}

ChildPage

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中看到的,我正在尝试使用

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

虽然这会显示MessageBox,但它不会显示Image。我做错了什么以及如何成功访问MainWindow Image

1 个答案:

答案 0 :(得分:0)

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