简体   繁体   English

C#WPF导航

[英]C# WPF Navigation

I am writing a WPF Appl. 我正在编写WPF应用程序。 in C#. 在C#中。 I got a MainWindow.xaml which contains an empty frame called MainFrame. 我得到一个MainWindow.xaml ,其中包含一个称为MainFrame的空框架。 I got four other pages called Welcome.xaml , Login.xaml , ObjectSelection.xaml and Exec.xaml . 我还有另外四个页面,分别称为Welcome.xamlLogin.xamlObjectSelection.xamlExec.xaml To navigate from MainWindow through the pages via the navigation buttons that are on the MainWindow , I simply can do this and call it on my buttons: 要通过MainWindow上的导航按钮在MainWindow浏览页面,我可以简单地做到这一点并在我的按钮上调用它:

private void PageNav1(object sender, RoutedEventArgs e)
{
    MainFrame.Content = new Welcome();
}

I have buttons in that Welcome Page that need to bring you to another page, let's say to the Login.xaml . 我在“欢迎页面”中有一些按钮需要将您带到另一个页面,比方说Login.xaml My approach was this: 我的方法是这样的:

private void SelectionExport(object sender, RoutedEventArgs e)
{
    MainWindow.MainFrame.Content = new Login();
}

But as usual I got an error: CS0120 An object reference is required for the non-static field, method, or property 'MainWindow.MainFrame' INTEGR8 但是像往常一样,我得到一个错误: CS0120 An object reference is required for the non-static field, method, or property 'MainWindow.MainFrame' INTEGR8

Any idea is greatly appreciated. 任何想法都将不胜感激。

You need to get a reference to the instance of the MainWindow class and access the Frame of this one: 您需要获取对MainWindow实例的引用,并访问该类的Frame

private void SelectionExport(object sender, RoutedEventArgs e)
{
    MainWindow mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
    mainWindow.MainFrame.Content = new Login();
}

As the Documentation says 正如文档所说

In order to use a non-static field, method, or property, you must first create an object instance. 为了使用非静态字段,方法或属性,必须首先创建一个对象实例。

For example, 例如,

public class MyClass 
{
    public void MyMethod() { }

    public static void MyStaticMethod() { }
}

MyClass.MyStaticMethod(); // Works
MyClass.MyMethod(); // CS0120

// You've got to do it like this

MyClass mc = new MyClass();
mc.MyMethod();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM