在 .NET 中使用 WPF 进行页面切换,通常有以下几种常见方法:

  1. 使用 Frame 控件

在 WPF 中,Frame 控件可以用来在不同的页面之间进行导航。你可以在 XAML 中定义一个 Frame 控件,然后在代码后台切换不同的页面。

XAML

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Frame x:Name="MainFrame" NavigationUIVisibility="Hidden"/>
    </Grid>
</Window>

C#

public MainWindow()
{
    InitializeComponent();
    NavigateToPage("Page1");
}

private void NavigateToPage(string pageName)
{
    MainFrame.Navigate(new Uri($"pack://application:,,,/Views/{pageName}.xaml", UriKind.Absolute));
}
  1. 使用 NavigationService 类

你可以创建一个 NavigationService 类来管理页面的导航。这种方法提供了更多的灵活性和控制。

NavigationService.cs

public class NavigationService
{
    private Frame _frame;

    public NavigationService(Frame frame)
    {
        _frame = frame;
    }

    public void Navigate(string pageName)
    {
        _frame.Navigate(new Uri($"pack://application:,,,/Views/{pageName}.xaml", UriKind.Absolute));
    }
}

MainWindow.xaml.cs

public MainWindow()
{
    InitializeComponent();
    NavigationService navigationService = new NavigationService(MainFrame);
    navigationService.Navigate("Page1");
}
  1. 使用 UserControl 控件和 ContentControl 动态切换内容

如果你想要更灵活地切换页面内容,你可以使用 ContentControl 和不同的 UserControl 控件。这种方式不需要使用 Frame。

XAML

<Window x:Class="YourNamespace.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <ContentControl x:Name="MainContent"/>
    </Grid>
</Window>

C#

public MainWindow()
{
    InitializeComponent();
    NavigateToPage(new UserControl1());
}

private void NavigateToPage(UserControl UserControl)
{
    MainContent.Content = UserControl;
}

总结:选择适合你的方法:

如果你的应用需要类似浏览器的前进、后退功能,使用 Frame。

如果需要更灵活的页面切换逻辑和内容管理,使用 ContentControl 和 UserControl。

如果需要更高级的导航管理和事件处理,使用自定义的 NavigationService 类。