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();
        }
    }
}
相关推荐
ghost1431 小时前
C#学习第22天:网络编程
开发语言·学习·c#
神仙别闹2 小时前
基于C#实现中央定位服务器的 P2P 网络聊天系统
服务器·网络·c#
阿蒙Amon3 小时前
DevExpress&WinForms-TreeList-数据绑定
c#·devexpress·winforms
bicijinlian5 小时前
.Net HttpClient 使用代理功能
c#·.net·httpclient·.net httpclient·httpclient 代理
敲代码的 蜡笔小新9 小时前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
程序猿多布10 小时前
使用Visual Studio将C#程序发布为.exe文件
c#·visual studio
老衲有点帅11 小时前
C#多线程Thread
开发语言·c#
PascalMing12 小时前
C# 通过脚本实现接口
c#·codeanalysis·接口派生
敲代码的 蜡笔小新16 小时前
【行为型之观察者模式】游戏开发实战——Unity事件驱动架构的核心实现策略
观察者模式·unity·设计模式·c#
向宇it16 小时前
【unity游戏开发——编辑器扩展】使用EditorGUI的EditorGUILayout绘制工具类在自定义编辑器窗口绘制各种UI控件
开发语言·ui·unity·c#·编辑器·游戏引擎