在WPF中如何从一个页面导航到另一个页面

7
我有一个MainWindow.XAMLCustomersView.XAML
当我在MainWindow上点击“Customer”按钮时,我想要导航到CustomersView.XAML并传递一些参数。
我可以使用NavigationService,但它仅适用于页面而不是窗口。此时,超链接不是一个选项。
这可能是一个相当简单的事情,但不确定如何使用MVVM来实现,而且不需要任何第三方控件。
3个回答

6
private void Navigate_Click(object sender, RoutedEventArgs e)//By Prince Jain 
{
   this.NavigationService.Navigate(new Uri("Page3.xaml", UriKind.Relative));
}

3
建议您对您的代码示例进行解释,说明它是如何工作并帮助回答问题的。 - Wtower

1

在WPF中,有许多选项可以从一个窗口导航到另一个窗口。您可以在MainWindow中使用一个框架,并在框架内导航所有页面。

<Window 
    x:Class="NavigationSample.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <DockPanel>
        <Frame x:Name="_mainFrame" />
    </DockPanel>
</Window>

从代码中,您可以这样告诉框架导航:

_mainFrame.Navigate(new Page1());

这恰好是一个有用的快捷方式,可以:
_mainFrame.NavigationService.Navigate(new Page1());

如果你使用PRISM之类的框架,你可以创建一个Shell来定义区域,并让你的页面导航到该Shell。
使用Prism Library 5.0 for WPF进行导航{{link1:}}

我可以不使用框架来完成这个吗? - Simsons
这可能会帮助您。http://wpfplayground.com/2014/06/04/navigation-model-for-simple-mvvm-applications/ - Jawahar

1

在XAML中的简单方法:

<Button HorizontalAlignment="Right" Name="continueButton" Width="75"
        Margin="0,0,8,11" Height="23" VerticalAlignment="Bottom"
        Click="continueButton_Click">
        Navigate
</Button>

C#:
private void continueButton_Click(object sender, RoutedEventArgs e)
{
    this.NavigationService.GoForward();
    //or
    this.NavigationService.Navigate("Second.xaml")
}

在MVVM XAML中:
<Button Command="{x:Static Views:Commands.NavigateHelp}"
        Content="Help"/>

在 Views 中(我们有一个包含所有这些的 Commands.cs 文件):
public static RoutedCommand NavigateHelp = new RoutedCommand();

在页面构造函数中,您可以连接这两个元素:
CommandBindings.Add(new CommandBinding(Commands.NavigateHelp,
    NavigateHelpExecute));

NavigateHelpExecute可以在代码后台中使用(这就是我们所做的),钩入ViewModel事件处理程序,或者其他方式。美妙的是,您可以像这样禁用其他导航:

CommandBindings.Add(new CommandBinding(NavigationCommands.Refresh, null));

这个 This.NavigationService 只能在 WPF 页面中使用,而不能在窗口中使用。我需要像问题中提到的那样在 WPF 窗口之间导航。 - Simsons
@Simsons 请通过此链接查看:http://www.codeproject.com/Articles/72724/Beginning-a-WPF-MVVM-application-Navigating-between - Dhru 'soni

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