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();
        }
    }
}
相关推荐
军训猫猫头2 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
不爱写代码的玉子4 小时前
HALCON透视矩阵
人工智能·深度学习·线性代数·算法·计算机视觉·矩阵·c#
明耀6 小时前
WPF DataGrid 默认显示行号
wpf
开开心心就好7 小时前
高效Excel合并拆分软件
开发语言·javascript·c#·ocr·排序算法·excel·最小二乘法
一名用户8 小时前
unity实现自定义粒子系统
c#·unity3d·游戏开发
lph197210 小时前
wpf的converter
wpf
fyifei055810 小时前
WPF学习PropertyChanged
wpf
钢铁男儿10 小时前
C# 类和继承(扩展方法)
java·servlet·c#
爱炸薯条的小朋友11 小时前
C#由于获取WPF窗口名称造成的异常报错问题
windows·c#·wpf
baivfhpwxf202311 小时前
wpf ListBox 去除item 单击样式
wpf