双屏应用程序,从第二个窗口在第一个窗口中访问方法

时间:2014-05-02 16:35:01

标签: c# wpf windows

我有一个适用于两个监视器的应用程序,在窗口1(mainWindow)中有一个框架,内容将在应用程序生命期间更改,在第二个窗口中内容始终相同。这是主窗口:

 void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {


         //main window content will load in a frame.
        if (Generics.loadingStatus == 0)
        {
            _mainFrame.Source = new Uri("Page1.xaml", UriKind.Relative);
            Generics.loadingStatus = 1;
        }

         SecondScreen win2 = new SecondScreen ();
        var secondaryScreen = System.Windows.Forms.Screen.AllScreens.Where(s => !s.Primary).FirstOrDefault();

        if (secondaryScreen != null)
        {
            if (!this.IsLoaded)
                win2.WindowStartupLocation = WindowStartupLocation.Manual;

            var workingArea = secondaryScreen.WorkingArea;

            win2.Left = workingArea.Left;
            win2.Top = workingArea.Top;
            win2.Width = workingArea.Width;
            win2.Height = workingArea.Height;

            // If window isn't loaded then maxmizing will result in the window displaying on the primary monitor
            if (win2.IsLoaded)
                win2.WindowState = WindowState.Maximized;

        }
        win2.Show();

    }

这在第二个窗口中:

 private void Window_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
    {

        Application curApp = Application.Current;
        var mainWnd = curApp.MainWindow as MainWindow;

        //ActualClass is a string variable that i set every time i change the content of the main frame in mainwindow
        if (mainWnd.ActualClass== "Page2.xaml")
        {
           //here i have to call a method of the Page2 class to launch an operation in Page2.cs only if the current page displayed in mainwindow frame is Page2.xaml

        }


    }

从第二个窗口我需要调用Page2.cs类的公共方法,我可以正确检查Page2.cs是否实际在主窗口中可视化(通过设置字符串变量)但我无法找到调用方法的类的当前实例...我该怎么做?

2 个答案:

答案 0 :(得分:1)

您是否尝试过访问数据上下文,例如

var myClass = mainWnd.DataContext as Page2Class;
myClass.MyMethod();

答案 1 :(得分:0)

以这种方式解决;

private void Window_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
{

    Application curApp = Application.Current;
    var mainWnd = curApp.MainWindow as MainWindow;

    //ActualClass is a string variable that i set every time i change the content of the main frame in mainwindow
    if (mainWnd.ActualClass== "Page2.xaml")
    {
       //here i have to call a method of the Page2 class to launch an operation in Page2.cs only if the current page displayed in mainwindow frame is Page2.xaml
           var content = mainWnd._mainFrame.Content as Page2Class;
            if (content != null)
            {
                content.Method();
            }
    }


}