WPF 多窗口分文件实现方案

项目文件结构

WindowSwitcher/
├── App.xaml
├── App.xaml.cs
├── MainWindow.xaml
├── MainWindow.xaml.cs
├── Views/
│   ├── SettingsWindow.xaml
│   ├── SettingsWindow.xaml.cs
│   ├── DataWindow.xaml
│   ├── DataWindow.xaml.cs
│   ├── HelpWindow.xaml
│   └── HelpWindow.xaml.cs
└── Services/└── WindowManager.cs

1. 主窗口 (MainWindow.xaml)

<Window x:Class="WindowSwitcher.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WindowSwitcher"Title="窗口切换管理器" Height="450" Width="800"><Grid><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><!-- 导航按钮区域 --><StackPanel Grid.Row="0" Orientation="Horizontal" Background="#f0f0f0" Padding="10"><Button Content="主窗口" Margin="5" Padding="10,5" Click="ShowMainWindow"/><Button Content="设置窗口" Margin="5" Padding="10,5" Click="ShowSettingsWindow"/><Button Content="数据窗口" Margin="5" Padding="10,5" Click="ShowDataWindow"/><Button Content="帮助窗口" Margin="5" Padding="10,5" Click="ShowHelpWindow"/><Button Content="退出应用" Margin="5" Padding="10,5" Click="ExitApplication" Background="#ffcccc" Foreground="DarkRed"/></StackPanel><!-- 主窗口内容 --><StackPanel Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center"><TextBlock Text="欢迎使用窗口切换管理器" FontSize="24" Margin="0,0,0,20"/><TextBlock Text="{Binding CurrentStatus}" FontSize="18" Foreground="#666"/><Button Content="刷新窗口状态" Margin="0,20,0,0" Padding="10,5" Click="RefreshStatus"/></StackPanel></Grid>
</Window>

2. 主窗口代码 (MainWindow.xaml.cs)

using WindowSwitcher.Services;
using System.Windows;namespace WindowSwitcher
{public partial class MainWindow : Window{private readonly WindowManager _windowManager = WindowManager.Instance;public string CurrentStatus => $"当前活动窗口: {_windowManager.ActiveWindow?.Title}";public MainWindow(){InitializeComponent();DataContext = this;// 初始化所有窗口_windowManager.InitializeWindows();// 显示主窗口_windowManager.ShowWindow<MainWindow>();}// 按钮事件处理private void ShowMainWindow(object sender, RoutedEventArgs e) => _windowManager.ShowWindow<MainWindow>();private void ShowSettingsWindow(object sender, RoutedEventArgs e) => _windowManager.ShowWindow<SettingsWindow>();private void ShowDataWindow(object sender, RoutedEventArgs e) => _windowManager.ShowWindow<DataWindow>();private void ShowHelpWindow(object sender, RoutedEventArgs e) => _windowManager.ShowWindow<HelpWindow>();private void ExitApplication(object sender, RoutedEventArgs e) => Application.Current.Shutdown();private void RefreshStatus(object sender, RoutedEventArgs e){// 刷新数据绑定OnPropertyChanged(nameof(CurrentStatus));}// 实现简单的属性变更通知public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;protected virtual void OnPropertyChanged(string propertyName){PropertyChanged?.Invoke(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));}}
}

3. 设置窗口 (Views/SettingsWindow.xaml)

<Window x:Class="WindowSwitcher.Views.SettingsWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="系统设置" Height="400" Width="600"><Grid Margin="20"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="Auto"/><RowDefinition Height="*"/></Grid.RowDefinitions><TextBlock Grid.Row="0" Text="系统设置" FontSize="20" FontWeight="Bold" Margin="0,0,0,20"/><StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,0,0,10"><TextBlock Text="主题:" Width="100" VerticalAlignment="Center"/><ComboBox Width="200"><ComboBoxItem Content="浅色主题"/><ComboBoxItem Content="深色主题" IsSelected="True"/></ComboBox></StackPanel><StackPanel Grid.Row="2" Orientation="Horizontal" Margin="0,0,0,10"><TextBlock Text="语言:" Width="100" VerticalAlignment="Center"/><ComboBox Width="200"><ComboBoxItem Content="中文"/><ComboBoxItem Content="English"/></ComboBox></StackPanel><StackPanel Grid.Row="3" Orientation="Horizontal" Margin="0,0,0,20"><TextBlock Text="自动保存:" Width="100" VerticalAlignment="Center"/><CheckBox IsChecked="True" VerticalAlignment="Center"/></StackPanel><Button Grid.Row="4" Content="返回主窗口" HorizontalAlignment="Center" Padding="10,5" Click="ReturnToMain" VerticalAlignment="Bottom"/></Grid>
</Window>

4. 设置窗口代码 (Views/SettingsWindow.xaml.cs)

using System.Windows;
using WindowSwitcher.Services;namespace WindowSwitcher.Views
{public partial class SettingsWindow : Window{private readonly WindowManager _windowManager = WindowManager.Instance;public SettingsWindow(){InitializeComponent();}private void ReturnToMain(object sender, RoutedEventArgs e){_windowManager.ShowWindow<MainWindow>();}}
}

5. 数据窗口 (Views/DataWindow.xaml)

<Window x:Class="WindowSwitcher.Views.DataWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="数据分析" Height="500" Width="700"><Grid Margin="15"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><TextBlock Grid.Row="0" Text="数据分析面板" FontSize="20" FontWeight="Bold" Margin="0,0,0,15"/><!-- 数据表格 --><DataGrid Grid.Row="1" AutoGenerateColumns="True" ItemsSource="{Binding DataItems}"><DataGrid.Columns><DataGridTextColumn Header="ID" Binding="{Binding Id}" Width="Auto"/><DataGridTextColumn Header="名称" Binding="{Binding Name}" Width="*"/><DataGridTextColumn Header="数值" Binding="{Binding Value}" Width="Auto"/><DataGridTextColumn Header="日期" Binding="{Binding Date, StringFormat=yyyy-MM-dd}" Width="Auto"/></DataGrid.Columns></DataGrid><StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,15,0,0"><Button Content="加载数据" Padding="10,5" Margin="0,0,10,0" Click="LoadData"/><Button Content="返回主窗口" Padding="10,5" Click="ReturnToMain"/></StackPanel></Grid>
</Window>

6. 数据窗口代码 (Views/DataWindow.xaml.cs)

using System.Windows;
using System.Collections.ObjectModel;
using WindowSwitcher.Services;namespace WindowSwitcher.Views
{public partial class DataWindow : Window{private readonly WindowManager _windowManager = WindowManager.Instance;// 数据模型public class DataItem{public int Id { get; set; }public string Name { get; set; }public double Value { get; set; }public DateTime Date { get; set; }}// 数据集合public ObservableCollection<DataItem> DataItems { get; } = new ObservableCollection<DataItem>();public DataWindow(){InitializeComponent();DataContext = this;// 初始加载一些示例数据LoadSampleData();}private void LoadSampleData(){DataItems.Clear();// 添加示例数据DataItems.Add(new DataItem { Id = 1, Name = "项目A", Value = 42.5, Date = DateTime.Now.AddDays(-2) });DataItems.Add(new DataItem { Id = 2, Name = "项目B", Value = 78.3, Date = DateTime.Now.AddDays(-1) });DataItems.Add(new DataItem { Id = 3, Name = "项目C", Value = 15.2, Date = DateTime.Now });}private void LoadData(object sender, RoutedEventArgs e){// 模拟加载更多数据int startId = DataItems.Count + 1;for (int i = 0; i < 5; i++){DataItems.Add(new DataItem {Id = startId + i,Name = $"新增项目{startId + i}",Value = new Random().NextDouble() * 100,Date = DateTime.Now.AddDays(-i)});}}private void ReturnToMain(object sender, RoutedEventArgs e){_windowManager.ShowWindow<MainWindow>();}}
}

7. 帮助窗口 (Views/HelpWindow.xaml)

<Window x:Class="WindowSwitcher.Views.HelpWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="帮助文档" Height="350" Width="500"><Grid Margin="15"><Grid.RowDefinitions><RowDefinition Height="Auto"/><RowDefinition Height="*"/><RowDefinition Height="Auto"/></Grid.RowDefinitions><TextBlock Grid.Row="0" Text="帮助与支持" FontSize="20" FontWeight="Bold" Margin="0,0,0,10"/><ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto"><TextBlock TextWrapping="Wrap"><Run FontWeight="Bold">如何使用窗口切换功能:</Run><LineBreak/>1. 点击顶部导航栏中的按钮可在不同窗口间切换<LineBreak/>2. 每个窗口都提供"返回主窗口"按钮<LineBreak/>3. 窗口状态会被保留,再次打开时保持上次的状态<LineBreak/><LineBreak/><Run FontWeight="Bold">常见问题:</Run><LineBreak/>Q: 为什么关闭按钮只是隐藏窗口?<LineBreak/>A: 这是设计选择,为了保持窗口状态并快速切换。要完全退出应用,请使用"退出应用"按钮。<LineBreak/><LineBreak/><Run FontWeight="Bold">技术支持:</Run><LineBreak/>如有任何问题,请联系 support@windowswitcher.com</TextBlock></ScrollViewer><Button Grid.Row="2" Content="返回主窗口" Padding="10,5" HorizontalAlignment="Center" Margin="0,15,0,0" Click="ReturnToMain"/></Grid>
</Window>

8. 帮助窗口代码 (Views/HelpWindow.xaml.cs)

using System.Windows;
using WindowSwitcher.Services;namespace WindowSwitcher.Views
{public partial class HelpWindow : Window{private readonly WindowManager _windowManager = WindowManager.Instance;public HelpWindow(){InitializeComponent();}private void ReturnToMain(object sender, RoutedEventArgs e){_windowManager.ShowWindow<MainWindow>();}}
}

9. 窗口管理器 (Services/WindowManager.cs)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows;
using WindowSwitcher.Views;namespace WindowSwitcher.Services
{public sealed class WindowManager{// 单例实例private static readonly Lazy<WindowManager> _instance = new Lazy<WindowManager>(() => new WindowManager());public static WindowManager Instance => _instance.Value;// 存储所有窗口实例private readonly Dictionary<Type, Window> _windows = new Dictionary<Type, Window>();// 当前活动窗口public Window ActiveWindow { get; private set; }private WindowManager() { }// 初始化所有窗口public void InitializeWindows(){// 创建主窗口CreateWindow<MainWindow>();// 创建其他窗口CreateWindow<SettingsWindow>();CreateWindow<DataWindow>();CreateWindow<HelpWindow>();}// 创建窗口实例private void CreateWindow<T>() where T : Window, new(){var windowType = typeof(T);if (!_windows.ContainsKey(windowType)){var window = new T();window.Closing += OnWindowClosing;_windows[windowType] = window;}}// 显示指定类型的窗口public void ShowWindow<T>() where T : Window{var windowType = typeof(T);if (_windows.TryGetValue(windowType, out Window window)){// 隐藏当前活动窗口if (ActiveWindow != null && ActiveWindow != window){ActiveWindow.Hide();}// 显示新窗口window.Show();window.Activate();window.Focus();ActiveWindow = window;}else{// 如果窗口尚未创建,则创建并显示CreateWindow<T>();ShowWindow<T>();}}// 窗口关闭事件处理private void OnWindowClosing(object sender, CancelEventArgs e){if (sender is Window window){// 阻止实际关闭,改为隐藏e.Cancel = true;window.Hide();// 如果关闭的是当前活动窗口,则激活主窗口if (ActiveWindow == window){ShowWindow<MainWindow>();}}}// 获取特定类型的窗口public T GetWindow<T>() where T : Window{return _windows.TryGetValue(typeof(T), out Window window) ? (T)window : null;}// 关闭所有窗口并退出public void ShutdownApplication(){// 关闭所有窗口foreach (var window in _windows.Values){window.Closing -= OnWindowClosing;window.Close();}_windows.Clear();Application.Current.Shutdown();}}
}

10. 应用程序入口 (App.xaml)

<Application x:Class="WindowSwitcher.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"StartupUri="MainWindow.xaml"><Application.Resources><!-- 全局样式可以放在这里 --></Application.Resources>
</Application>

11. 应用程序入口代码 (App.xaml.cs)

using System.Windows;
using WindowSwitcher.Services;namespace WindowSwitcher
{public partial class App : Application{protected override void OnStartup(StartupEventArgs e){base.OnStartup(e);// 初始化窗口管理器var windowManager = WindowManager.Instance;windowManager.InitializeWindows();}protected override void OnExit(ExitEventArgs e){// 清理资源WindowManager.Instance.ShutdownApplication();base.OnExit(e);}}
}

关键实现说明

1. 分文件组织

  • MainWindow:主窗口,作为应用入口
  • Views文件夹:包含所有其他窗口(设置、数据、帮助)
  • Services文件夹:包含窗口管理器服务

2. 窗口管理器核心功能

// 创建窗口
private void CreateWindow<T>() where T : Window, new()
{var windowType = typeof(T);if (!_windows.ContainsKey(windowType)){var window = new T();window.Closing += OnWindowClosing;_windows[windowType] = window;}
}// 切换窗口
public void ShowWindow<T>() where T : Window
{// ...window.Show();window.Activate();window.Focus();ActiveWindow = window;
}// 处理关闭事件
private void OnWindowClosing(object sender, CancelEventArgs e)
{e.Cancel = true; // 阻止实际关闭window.Hide();   // 改为隐藏
}

3. 数据绑定示例

在数据窗口中,展示了如何使用数据绑定:

// 数据模型
public class DataItem
{public int Id { get; set; }public string Name { get; set; }public double Value { get; set; }public DateTime Date { get; set; }
}// 数据集合
public ObservableCollection<DataItem> DataItems { get; } = new ObservableCollection<DataItem>();// XAML绑定
<DataGrid ItemsSource="{Binding DataItems}">

4. 属性变更通知

在主窗口中实现了简单的属性变更通知:

public string CurrentStatus => $"当前活动窗口: {_windowManager.ActiveWindow?.Title}";// 刷新方法
private void RefreshStatus(object sender, RoutedEventArgs e)
{OnPropertyChanged(nameof(CurrentStatus));
}// 实现INotifyPropertyChanged
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

使用说明

  1. 项目结构

    • 创建一个新的WPF应用程序项目
    • 按上述文件结构组织代码
  2. 启动应用

    • 应用程序启动时会初始化所有窗口
    • 主窗口首先显示
  3. 窗口切换

    • 使用顶部导航栏按钮在不同窗口间切换
    • 每个窗口都有返回主窗口的按钮
  4. 关闭窗口

    • 点击关闭按钮实际上是隐藏窗口
    • 使用"退出应用"按钮完全关闭程序
  5. 数据保持

    • 每个窗口的状态在切换时保持不变
    • 数据窗口中的数据在重新打开时保持

这种分文件实现方式使代码结构清晰,便于维护和扩展,同时保持了窗口切换的高性能和状态保持特性。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.pswp.cn/pingmian/89522.shtml
繁体地址,请注明出处:http://hk.pswp.cn/pingmian/89522.shtml
英文地址,请注明出处:http://en.pswp.cn/pingmian/89522.shtml

如若内容造成侵权/违法违规/事实不符,请联系英文站点网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

在服务器(ECS)部署 MySQL 操作流程

在部署 MySQL 数据库之前需要准备好服务器环境。可以通过以下两种方式来准备部署服务器&#xff1a;云服务器&#xff08;ECS&#xff09;&#xff0c;如&#xff1a;阿里云、华为云、腾讯云等。IDC服务器。 现以阿里云服务器&#xff08;ECS&#xff09;Windows版本来进行部署…

Java File 类详解:从基础操作到实战应用,掌握文件与目录处理全貌

作为一名 Java 开发工程师&#xff0c;你一定在实际开发中遇到过需要操作文件或目录的场景&#xff0c;例如&#xff1a;读写配置文件、上传下载、日志处理、文件遍历、路径管理等。Java 提供了 java.io.File 类来帮助开发者完成这些任务。本文将带你全面掌握&#xff1a;File …

嵌入式学习-PyTorch(9)-day25

进入尾声&#xff0c;一个完整的模型训练 &#xff0c;点亮的第一个led#自己注释版 import torch import torchvision.datasets from torch import nn from torch.utils.tensorboard import SummaryWriter import time # from model import * from torch.utils.data import Dat…

用AI做带货视频评论分析进阶提分【Datawhale AI 夏令营】

文章目录回顾赛题优化1️⃣优化2️⃣回顾赛题 模块内容类型说明/示例赛题背景概述参赛者需构建端到端评论分析系统&#xff0c;实现商品识别、多维情感分析、评论聚类与主题提炼三大任务。商品识别输入video_desc&#xff08;视频描述&#xff09; video_tags&#xff08;标签…

Redis常见数据结构详细介绍

Redis 作为一款高性能的开源内存数据库&#xff0c;凭借其丰富多样的数据结构和出色的性能&#xff0c;在缓存、会话存储、实时分析等众多场景中得到了广泛应用。下面将详细介绍 Redis 主要的数据结构&#xff0c;包括它们的类型、具体用法和适用场景。1、字符串&#xff08;St…

HAMR硬盘高温写入的可靠性问题

热辅助磁记录(HAMR)作为突破传统磁记录密度极限的下一代存储技术,其在数据中心大规模应用的核心挑战在于可靠性保障。 扩展阅读: 下一个存储战场:HAMR技术HDD HAMR技术进入云存储市场! 漫谈HAMR硬盘的可靠性 随着存储密度向4Tbpsi迈进,传统磁记录技术遭遇"三难困境…

使用llama-factory进行qwen3模型微调

运行环境 Linux 系统(ubuntu) Gpu (NVIDIA) 安装部署 llama factory CUDA 安装 首先,在 https://developer.nvidia.com/cuda-gpus 查看您的 GPU 是否支持CUDA 保证当前 Linux 版本支持CUDA. 在命令行中输入 uname -m && cat /etc/*release,应当看到类似的输出 x8…

tcp/udp调试工具

几款tcp/udp调试工具 下载地址&#xff1a;夸克网盘

智慧光伏发电信息化系统需求文档

以下是从产品经理角度撰写的智慧光伏发电信息化系统需求文档&#xff0c;聚焦光伏行业痛点与业务价值&#xff0c;遵循标准PRD结构&#xff1a;智慧光伏发电信息化系统需求文档 版本&#xff1a;1.0 日期&#xff1a;2025年7月19日 作者&#xff1a;产品经理视角一、文档概述 1…

ARCS系统机器视觉实战(直播回放)

ARCS系统机器视觉实战本次培训主要围绕ARCS操作系统中的视觉与机器人同步应用展开&#xff0c;详细讲解了网络配置、视觉软件设置、九点标定、机器人程序编写以及数据通信等内容。以下是关键要点提炼&#xff1a; 网络配置 为机器人、相机和电脑分别设置静态IP地址&#xff0c;…

Http请求中的特殊字符

问题 一个 springboot 应用&#xff0c;包含如下 controller RestController public class DemoController {GetMapping("/get")public ResponseEntity<String> get(RequestParam(value "cid2") String cid2) 准备测试数据 String cid2 "…

告别手动报表开发!描述数据维度,AI 自动生成 SQL 查询 + Java 导出接口

Java 开发中&#xff0c;报表模块往往是 “隐形耗时大户”—— 产品经理要 “按地区、月份统计订单量”&#xff0c;开发者需先编写 SQL 查询&#xff0c;再手动开发导出接口&#xff0c;稍作调整又要重新调试&#xff0c;耗费大量时间在重复劳动上。飞算 JavaAI 通过 “数据维…

函数设计测试用例

//归并排序:public static void mergeSort(int[] a,int left,int right){if(left > right)return;int mid left(right -left)/2;mergeSort(a,left,mid);mergeSort(a,mid1,right);int[] tmp new int[a.length];int l left,r mid1,k left;while(l<mid && r<…

Vmware虚拟机使用仅主机模式共享物理网卡访问互联网

一、概述 Vmware虚拟机网卡模式有三种&#xff1a;桥接模式、仅主机模式、NAT模式。默认情况下&#xff0c;Vmware虚拟机使用仅主机模式不能访问互联网。因此&#xff0c;虚拟机可以共享宿主机的物理网卡访问互联网。 三种网卡模式的区别二、Vmware网络设置 2.1、调整虚拟网络 …

声画同步!5 个音视频素材适配的网站,创作更和谐

视频画面和背景音乐不搭&#xff1f;音效和动作不同步&#xff1f;好的作品&#xff0c;声音和画面必须像齿轮一样咬合。这 5 个专注 “声画同步” 的素材网站&#xff0c;能让音视频素材精准匹配&#xff0c;从旋律到节奏&#xff0c;从音效到画面&#xff0c;都默契十足&…

13.多种I/O函数

前言 之前的示例中&#xff0c;基于Linux的使用read&write函数完成数据I/O&#xff0c;基于Windows的则使用send&recv函数。这次的Linux示例也将使用send& recv函数&#xff0c;并讲解其与read&write函数相比的优点。还将介绍几种其他的I/O函数。 一、send &am…

设计模式五:桥模式(Bridge Pattern)

桥模式是一种结构型设计模式&#xff0c;它将抽象部分与其实现部分分离&#xff0c;使它们可以独立变化。这种模式通过提供桥梁结构将抽象和实现解耦。桥模式的结构桥模式包含以下主要角色&#xff1a;Abstraction&#xff08;抽象类&#xff09;&#xff1a;定义抽象接口&…

深入理解设计模式之模板模式:优雅地定义算法骨架

在软件开发中&#xff0c;我们经常会遇到这样的情况&#xff1a;多个类执行相似的操作流程&#xff0c;但每个类在流程的某些步骤上有自己特定的实现。如果为每个类都完整地编写整个流程&#xff0c;会导致大量重复代码&#xff0c;且难以维护。这时候&#xff0c;模板模式&…

基于单片机宠物喂食器/智能宠物窝/智能饲养

传送门 &#x1f449;&#x1f449;&#x1f449;&#x1f449;其他作品题目速选一览表 &#x1f449;&#x1f449;&#x1f449;&#x1f449;其他作品题目功能速览 概述 深夜加班时&#xff0c;你是否担心家中宠物饿肚子&#xff1f;出差旅途中&#xff0c;是否焦虑宠…

静态补丁脚本 - 修改 libtolua.so

直接改arm64的so&#xff0c; 使用python脚本。#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ 静态补丁脚本 - 修改 libtolua.so 主要功能&#xff1a; 1. 修改 luaL_loadbuffer 函数&#xff0c;将跳转目标从 luaL_loadbufferx 改为 luaL_loadfilex 2. …