WPF 简单页面切换示例

原理比较简单,但是有个坑,为了使界面能够正确更新,记得使用 INotifyPropertyChanged 接口来实现属性更改通知。

html 复制代码
<Window x:Class="PageTest.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:PageTest"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="0.1*"/>
            <RowDefinition/>
        </Grid.RowDefinitions>

        <StackPanel Orientation="Horizontal">
            <Button Width="50" Height="25" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="5" Click="Button_Click"></Button>
            <Button Width="50" Height="25" VerticalAlignment="Top" HorizontalAlignment="Left" Margin="5" Click="Button_Click_1"></Button>
        </StackPanel>

        <Frame Grid.Row="1" Content="{Binding CurMain}" NavigationUIVisibility="Hidden"></Frame>
    </Grid>
</Window>
csharp 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace PageTest
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    [AddINotifyPropertyChangedInterface]
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            DataContext = this;
        }

        object curMain;

        public object CurMain { get => curMain; set => curMain = value; }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            CurMain = new Page1();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            CurMain = new Page2();
        }
    }
}
相关推荐
.NET修仙日记8 小时前
2026 .NET 面试八股文:高频题 + 答案 + 原理(高级核心篇)
面试·职场和发展·c#·.net·.net core·.net 8
唐青枫10 小时前
终于不用手搓两级缓存了!C#.NET HybridCache 详解:L1 L2、标签失效与防击穿实战
c#·.net
hixiong1231 天前
C# OpenvinoSharp使用DINOv2模型进行图像相似度计算
开发语言·c#
月昤昽1 天前
autoCAD二次开发 4.正多边形与collection区分
算法·c#·二次开发·autocad二次开发
Victory_20251 天前
c#定时器顺序控制写法
开发语言·c#·c#顺序控制+定时器
雪度娃娃1 天前
基于TCP的网络词典
网络·c++·tcp/ip·c#
秋の本名1 天前
第一章 鸿蒙生态架构与开发理念
华为·wpf·harmonyos
xxjj998a1 天前
PHP vs C#:两大编程语言终极对比
开发语言·c#·php
工程师0071 天前
C# 泛型:约束、协变逆变、底层模板生成机制
c#·泛型·逆变·协变