C# WPF页面间导航(视图)

dced5bon  于 7个月前  发布在  C#
关注(0)|答案(3)|浏览(129)

我正在尝试创建一个类和方法,可以在任何窗口和页面上使用,以更改主窗口上显示的当前页面。
到目前为止,我得到了:

class MainWindowNavigation : MainWindow
{
    public MainWindow mainWindow;

   public void ChangePage(Page page)
    {
        mainWindow.Content = page;
    }
}

字符串
主窗口本身:

public MainWindow()
    {
        InitializeComponent();
        MainWindowNavigation mainWindow = new MainWindowNavigation();
        mainWindow.ChangePage(new Pages.MainWindowPage());
    }


不幸的是,这最终导致System.StackOverflowException。
创建这个的主要原因是我希望能够从当前显示在mainWindow.Content中的页面更改mainWindow.Content。
我已经审查了MVVM,但我不认为这是值得使用它的一个小应用程序一样,因为所有我希望它做的是显示一个欢迎页面打开,然后在一边会有几个按钮.一旦按下mainWindow.内容正确地更改到一个页面,用户可以输入登录详细信息,然后在按钮上按下登录页面我想改变mainWindow.内容到不同的页面上成功验证输入的登录详细信息。

vddsk6oq

vddsk6oq1#

使用MVVM是绝对好的,因为它将简化您的需求的实现。WPF是为与MVVM模式一起使用而构建的,这意味着大量使用数据绑定和数据模板。
任务很简单,为每个视图创建一个UserControl(或DataTemplate),例如,WelcomePageLoginPage及其相应的视图模型WelcomePageViewModelLoginPageViewModel
ContentControl将显示页面。
主要的技巧是,当使用隐式DataTemplate(没有定义x:Key的模板资源),XAML解析器将自动查找并应用正确的模板,其中DataType匹配ContentControl的当前内容类型。这使得导航非常简单,因为您只需从页面模型集合中选择当前页面,并通过数据绑定将此页面设置为ContentControlContentPresenterContent属性:

用法

主窗口.xaml

<Window>
  <Window.DataContext>
    <MainViewModel />
  </Window.DataContext>

  <Window.Resources>
    <DataTemplate DataType="{x:Type WelcomePageviewModel}">
      <WelcomPage />
    </DataTemplate>

    <DataTemplate DataType="{x:Type LoginPageviewModel}">
      <LoginPage />
    </DataTemplate>
  </Window.Resources>

  <StackPanel>
  
    <!-- Page navigation -->
    <StackPanel Orientation="Horizontal">
      <Button Content="Show Login Screen" 
              Command="{Binding SelectPageCommand}" 
              CommandParameter="{x:Static PageName.LoginPage}" />
      <Button Content="Show Welcome Screen" 
              Command="{Binding SelectPageCommand}" 
              CommandParameter="{x:Static PageName.WelcomePage}" />
    </StackPanel>
  
    <!-- 
      Host of SelectedPage. 
      Automatically displays the DataTemplate that matches the current data type 
    -->
    <ContentControl Content="{Binding SelectedPage}" />
  <StackPanel>
</Window>

字符串

实现

1.创建单独的页面控件(承载页面内容的控件)。这可以是ControlUserControlPage或简单的DataTemplate

欢迎页面.xaml

<UserControl>
      <StackPanel>
        <TextBlock Text="{Binding PageTitle}" />
        <TextBlock Text="{Binding Message}" />
      </StackPanel>
    </UserControl>

登录页面.xaml

<UserControl>
      <StackPanel>
        <TextBlock Text="{Binding PageTitle}" />
        <TextBox Text="{Binding UserName}" />
      </StackPanel>
    </UserControl>


1.创建页面模型:

IPage.cs

interface IPage : INotifyPropertyChanged
    {
      string PageTitel { get; set; }
    }

WelcomePageViewModel.cs

class WelcomePageViewModel : IPage
    {
      private string pageTitle;   
      public string PageTitle
      {
        get => this.pageTitle;
        set 
        { 
          this.pageTitle = value; 
          OnPropertyChanged();
        }
      }

      private string message;   
      public string Message
      {
        get => this.message;
        set 
        { 
          this.message = value; 
          OnPropertyChanged();
        }
      }

      public WelcomePageViewModel()
      {
        this.PageTitle = "Welcome";
      }

      public event PropertyChangedEventHandler PropertyChanged;
      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
    }

LoginPageViewModel.cs

class LoginPageViewModel : IPage
    {
      private string pageTitle;   
      public string PageTitle
      {
        get => this.pageTitle;
        set 
        { 
          this.pageTitle = value; 
          OnPropertyChanged();
        }
      }

      private string userName;   
      public string UserName
      {
        get => this.userName;
        set 
        { 
          this.userName = value; 
          OnPropertyChanged();
        }
      }

      public LoginPageViewModel()
      {
        this.PageTitle = "Login";
      }

      public event PropertyChangedEventHandler PropertyChanged;
      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
      {
        this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
      }
    }


1.创建页面标识符的枚举(以消除XAML和C#中的魔术字符串):

PageName.cs

public enum PageName
    {
      Undefined = 0, WelcomePage, LoginPage
    }


1.创建MainViewModel来管理页面及其导航:

MainViewModel.cs

RelayCommand的实现可以在

  • Microsoft Excel:Patterns - WPF Apps With The Model-View-ViewModel Design Pattern - Relaying Command Logic*
class MainViewModel
    {
      public ICommand SelectPageCommand => new RelayCommand(SelectPage);

      private Dictionary<PageName, IPage> Pages { get; }

      private IPage selectedPage;   
      public IPage SelectedPage
      {
        get => this.selectedPage;
        set 
        { 
          this.selectedPage = value; 
          OnPropertyChanged();
        }
      }

      public MainViewModel()
      {
        this.Pages = new Dictionary<PageName, IPage>
        {
          { PageName.WelcomePage, new WelcomePageViewModel() },
          { PageName.LoginPage, new LoginPageViewModel() }
        };

        this.SelectedPage = this.Pages.First().Value;
      }

      public void SelectPage(object param)
      {
        if (param is PageName pageName 
          && this.Pages.TryGetValue(pageName, out IPage selectedPage))
        {
          this.SelectedPage = selectedPage;
        }
      }

      public event PropertyChangedEventHandler PropertyChanged;
      protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) 
        => this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

krugob8w

krugob8w2#

您可能希望将MainWindowNavigation定义为一个静态类,并使用一个方法简单地更改当前MainWindowContent

static class MainWindowNavigation
{
    public static void ChangePage(Page page)
    {
        var mainWindow = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
        if (mainWindow != null)
            mainWindow.Content = page;
    }
}

字符串
然后,您可以从任何类调用该方法,而无需引用MainWindow

MainWindowNavigation.ChangePage(new Pages.MainWindowPage());

cxfofazt

cxfofazt3#

我发现了一个解决方案,如何在不将所有对象初始化存储在内存中的情况下进行简化导航。在我看来,这个解决方案允许您保存MVVM模式并实现更少的内存开销。

MainWindow.xaml

<Window x:Class="TestWpf.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:TestWpf"
    mc:Ignorable="d" Title="MainWindow" Height="450" Width="800">
<Grid Background="Green">
    
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Orientation="Horizontal" Grid.Row="0">
        <Button Content="Go to login" Command="{Binding NavigateCmd}" CommandParameter="{x:Type local:LoginPage}"/>
    </StackPanel>
    <Frame Grid.Row="1" Content="{Binding SelectedContent, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}"
                    HorizontalAlignment="Center" Width="200" Height="200"/>
</Grid>

</Window>

字符串

MainWindowViewModel.cs

public partial class MainWindowViewModel : INotifyPropertyChanged 
{
private object? content;

public MainWindowViewModel()
{
    NavigateCmd = new RelayCommand<object>(Navigate);
}

public event PropertyChangedEventHandler? PropertyChanged;
protected void OnPropertyChanged([CallerMemberName]string? name = null)
{
    PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}

public object? SelectedContent { get => content; set { content = value; OnPropertyChanged(); } }

public RelayCommand<object> NavigateCmd { get; }
private void Navigate(object? param = null)
{
    if (param is Type type == false) return;
    SelectedContent = Activator.CreateInstance(type);
    ((FrameworkElement)SelectedContent).DataContext = this; //could be any data context;
}
}

LoginPage.xaml

<Page x:Class="TestWpf.LoginPage"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  xmlns:local="clr-namespace:TestWpf"
  mc:Ignorable="d" 
  d:DesignHeight="450" d:DesignWidth="800"
  Title="LoginPage">

<Grid Background="Red">
    
</Grid>


当点击“Go to login”按钮时,它将调用NaviateCmd命令,该命令又将调用方法Navigate并传递PageType,您希望在MainWindow.xaml中显示。然后在方法Navigate中创建页面的示例,设置必要的数据绑定并将其放置在SelectedContent属性中。
如果您想将导航设置为不同的页面,您可以在ButtonCommandParameter属性中传递所需页面的不同Type

相关问题