如何在XAML页面之间进行导航?

9
我有2个页面,需要从mainpage.xaml导航到login.page xaml,但是它抛出了对象引用未设置为对象的实例,在Root.Children.Clear()中...。
我在App.xaml中添加了以下代码:
   private void Application_Startup(object sender, StartupEventArgs e)
        {
            Grid myGrid = new Grid();
            myGrid.Children.Add(new MainPage());
            this.RootVisual = myGrid;
       }

然后我在main.xaml上添加了一些代码以导航到LoginUI.xaml。
namespace Gen.CallCenter.UI
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            Grid Root = ((Grid)(this.Parent));
            Root.Children.Clear();
            Root.Children.Add(new LoginUI());
        }
    }
}

如何从 main.xaml 导航到 LoginUI.xaml?
6个回答

13

假设您正在查看MainPage.xaml,然后想要通过单击 ButtonImageEditMainPage.xaml中打开名为newPage.xaml的另一个xaml页面,这里是您应在MainPage.xaml.cs中编写的快速解决方案:

private void imageEdit1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    newPage mynewPage = new newPage(); //newPage is the name of the newPage.xaml file
    this.Content = mynewPage;
}

这对我而言是有效的。


对我也起作用...如果您已经有了按钮控件的 private void Button_Click_1(object sender, RoutedEventArgs e),那么不要复制第一行,除此之外都完美且容易。 - DevCompany
虽然它一直在工作,但URL似乎没有改变。 - Ramesh Durai

11

AnthonyWJones所说,您需要使用导航框架。

首先,您需要在项目中添加对System.Windows.Controls.Navigation的引用,并在您的MainPage.xaml中进行引用。

xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"

那么您需要一个框架,在其中切换不同的XAML页面。类似这样:

<navigation:Frame x:Name="navFrame" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" Source=”/Views/First.xaml” />

现在在MainPage.xaml中你可能会有一个带有标签的按钮

<Button Click="Button_Click" Tag="/Views/Second.xaml" Content="Second" />

Button_Click事件处理程序中,你可以切换navFrame中显示的内容。

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button theButton = sender as Button;
    string url = theButton.Tag.ToString();

    this.navFrame.Navigate(new Uri(url, UriKind.Relative));
}

值得注意的一个很酷的事情是,通过使用NavigationFramework,浏览器的后退和前进按钮可以完美地工作,并且地址栏中的URL会根据您当前所在的XAML页面进行更新 :)


2

看起来你可能走错了方向。使用导航应用程序模板可以解决这种情况。你应该启动一个新项目并选择“Silverlight导航应用程序”。

一旦加载,只需运行它以查看基本外壳的外观。然后查看MainPage如何结构化和Home视图。你需要做的是创建基于导航Page类型的新视图,然后将它们添加到MainPage.xaml中。


2

1
private void formcombobox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    foreach (ComboBoxItem child in formcombobox.Items)
    {
        if (child.Name != null && child.IsSelected == true)
        {

            string url = new System.Uri("/DWRWefForm;component/Pages/"
                            + child.Name + ".xaml", System.UriKind.Relative).ToString();
            this.navframe.Navigate(new Uri(url, UriKind.Relative)); 
        }

    }
}

1

试试这个:

private void imageEdit1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    newPage mynewPage = new newPage(); //newPage is the name of the newPage.xaml file
    this.Content = mynewPage;
}

对我来说它正在工作。:)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接