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();
        }
    }
}
相关推荐
我笔记9 分钟前
.net过滤器和缓存
c#
夏子曦9 小时前
C#内存管理深度解析:从栈堆原理到高性能编程实践
开发语言·c#
分布式存储与RustFS9 小时前
告别复杂配置:用Milvus、RustFS和Vibe Coding,60分钟DIY专属Chatbot
wpf·文件系统·milvus·对象存储·minio·rustfs·vibe
William_cl13 小时前
C# MVC网页调试的方法
开发语言·c#·mvc
小小的技术员13 小时前
C# 无实体生成JSON字符串
c#·json
L X..19 小时前
Unity反射调用 ReactiveProperty<T>(泛型类型)内部方法时崩溃
unity·c#·游戏引擎·.net
攻城狮CSU21 小时前
WPF 绑定机制实现原理
wpf
攻城狮CSU21 小时前
WPF 之数据绑定一(Data Binding)
wpf
缺点内向1 天前
C# 中 Excel 工作表打印前页面边距的设置方法
c#·.net·excel
雪芽蓝域zzs1 天前
uniapp AES 加密解密
开发语言·uni-app·c#