WPF手動實現切換頁面

孤沉發表於2024-08-28

1、首先主頁面

  <Grid>
      <Grid.ColumnDefinitions>
          <ColumnDefinition Width="220" />
          <ColumnDefinition />
      </Grid.ColumnDefinitions>

      <Grid Grid.Column="1">
          <Grid.RowDefinitions>
              <RowDefinition />
              <RowDefinition Height="auto"/>
          </Grid.RowDefinitions>
          <ContentControl Content="{Binding CurrentView}" />
          <Button
              Width="200"
              Height="30"
              Grid.Row="1"
              HorizontalAlignment="Right"
              VerticalAlignment="Bottom"
              Command="{Binding NextPageCommand}"
              Content="{Binding Content}" />
      </Grid>
  </Grid>

2、接著ViewModel程式碼

 public class MainWindowViewModel : BindableBase
 {
     private PageType _currentPage = PageType.One;

     public string Content
     {
         get => _currentPage == PageType.One ? "下一頁" : "返回";
         set => SetProperty(ref _currentPage, value == "下一頁" ? PageType.One : PageType.Two);
     }

     private UserControl _currentView;

     public UserControl CurrentView
     {
         get => _currentView;
         set => SetProperty(ref _currentView, value);
     }

     public ICommand NextPageCommand { get; set; }

     public MainWindowViewModel()
     {
         NextPageCommand = new DelegateCommand(Execute);
         CurrentView = MainContent.PageDict[PageType.One.ToString()];
     }

     private void Execute()
     {
         _currentPage = _currentPage == PageType.One ? PageType.Two : PageType.One;
         Content = Content; 
         CurrentView = MainContent.PageDict[_currentPage.ToString()];
     }
 }

 public class MainContent
 {
     public static Dictionary<string, UserControl> PageDict = new Dictionary<string, UserControl>();
    
     static MainContent()
     {
         Init();
     }
     public static void Init()
     {
         PageDict.Add("One", new OnePageView());
         PageDict.Add("Two", new TwoPageView());
     }
 }
 public enum PageType
 {
     One,
     Two
 }

相關文章