C# WPF 窗体切换

概述

     这是粉丝反馈的一个问题:具体如下:

在首页用DockPanel.Dock把界面分成上下左右

在首页右面加载了一个窗口1,窗口1里有个按钮,点击按钮

首页的右面加载窗口2.

今天抽空写了写了个实例替他解答一下!.

代码部分

     大概实现的步骤:首先定义两个窗体:form1和form2,然后在主窗体右侧先绑定form1,然后点击form1上的按钮后,通过委托事件更改主窗体绑定的值

主窗体前台代码:这里通过RightTestView绑定窗体到主页面

<UserControl x:Class="Caliburn.Micro.Hello.TestFormView"             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"              xmlns:d="http://schemas.microsoft.com/expression/blend/2008"              xmlns:local="clr-namespace:Caliburn.Micro.Hello"              xmlns:cal="http://www.caliburnproject.org"             mc:Ignorable="d"              d:DesignHeight="450" d:DesignWidth="800">    <DockPanel>        <Button DockPanel.Dock="Left" Content="ButtonLeft"></Button>        <Button DockPanel.Dock="Top" Content="ButtonTop"></Button>        <ContentControl DockPanel.Dock="Right" cal:View.Model="{Binding RightTestView}"  MinWidth="300"></ContentControl>        <Button DockPanel.Dock="Bottom" Content="ButtonBottom"></Button>        <Button  Content="Center"></Button>    </DockPanel></UserControl>

后台cs代码:这里订阅了一个ShowNewWindow事件,触发后更改界面显示

using Caliburn.Micro.Hello.Models;using PropertyChanged;namespace Caliburn.Micro.Hello{    [AddINotifyPropertyChangedInterface]    public class TestFormViewModel : Screen, IViewModel    {        public IViewModel RightTestView { get; set; }        public TestFormViewModel()        {            DisplayName = "TestForm";            RightTestView = new FirstTestViewModel();            CommonEvent.ShowFrom += ShowNewWindow;        }        public void ShowNewWindow(bool isShow)        {            if (isShow)            {                RightTestView = new SecondTestViewModel();            }            else            {                RightTestView = new FirstTestViewModel();            }        }    }}
 public class CommonEvent    {        public static Action<bool> ShowFrom =  delegate{};    }

窗体1后台代码:

   public void ShowNewWindow()        {                        MessageBox.Show("我是第一个窗体");            CommonEvent.ShowFrom.Invoke(true);        }

窗体2后台代码:

 public void ShowNewWindow()        {            MessageBox.Show("我是第二个窗体");            CommonEvent.ShowFrom.Invoke(false);        }

效果演示

   

C# WPF 窗体切换

源码下载

   

链接:https://pan.baidu.com/s/1vZMCYf3HPYBk9XQth5xisw

提取码:6666