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();
        }
    }
}
相关推荐
wangnaisheng2 小时前
【C#】RocketMQ、Redis的使用
c#
阿蒙Amon2 小时前
C#每日面试题-接口和抽象类的区别
开发语言·c#
ejjdhdjdjdjdjjsl4 小时前
深入理解C#泛型:从方法到约束
c#
bugcome_com4 小时前
WPF 核心布局控件全解析:从 Grid 到 UniformGrid 的实战应用
c#·wpf
wangnaisheng5 小时前
Intel IPP 图像处理相关函数
c++·c#·图像
阿蒙Amon5 小时前
C#每日面试题-简述可空类型
microsoft·面试·c#
huluang5 小时前
高性能Word文档批注处理器的设计与实现
开发语言·c#·word
观无5 小时前
WPF-Datagrid控件的无缝滚动
wpf
Lv11770086 小时前
Visual Studio中的try -- catch
ide·笔记·c#·visual studio
先生沉默先6 小时前
串口通信学习,使用winform读取串口发送数据,(2)
学习·c#·串口