首先介绍MainWindow.xaml
<Window x:Class="Sys.MainWindow"xmlns="/winfx//xaml/presentation"xmlns:x="/winfx//xaml"xmlns:d="/expression/blend/"xmlns:mc="/markup-compatibility/"xmlns:local="clr-namespace:Sys"xmlns:loc="clr-namespace:Sys.WinForm"xmlns:sys="clr-namespace:System;assembly=mscorlib"xmlns:myLocal="clr-namespace:Sys.Util"xmlns:myLocalCommon="clr-namespace:mon"xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"mc:Ignorable="d"PreviewKeyDown="WinMain_PreviewKeyDown"PreviewKeyUp="WinMain_PreviewKeyUp"Style="{StaticResource CustomWindowStyle}"Name ="WinMain" Height="768" Width="1024" WindowStartupLocation="CenterScreen" Closing="WinMain_Closing"><Window.Resources>
其中是FrameworkElement 类的一些属性配置,Height和Width就是窗口的高和宽,WindowStartupLocation可设置窗口初始化时的位置。还可用Maxheight和Minheight来设置最大和最小值。
SizeToContent="WidthAndHeight" 窗体的尺寸将随内容而变化,这个可以保证窗口内的控件都能展示出来。
而想要让窗口根据不同的电脑大小展示不同大小的窗口则需要获得屏幕的大小
double x = SystemParameters.WorkArea.Width;//得到屏幕工作区域宽度double y = SystemParameters.WorkArea.Height;//得到屏幕工作区域高度double x1= SystemParameters.PrimaryScreenWidth;//得到屏幕整体宽度double y1 = SystemParameters.PrimaryScreenHeight;//得到屏幕整体高度
直接在MainWindow.xaml.cs 中的private MainWindow()
加入
double width = SystemParameters.PrimaryScreenWidth;double height = SystemParameters.PrimaryScreenHeight;this.Width = width * (0.7);this.Height = height * (0.7);
0.7就表示的是高或宽的70%
发现一个问题,当子窗口下开启一个窗口再关闭后,会导致主窗口自动最小化。目前解决方式:
在子窗口.closed(); 后加入
MainWindow.GetInstance().Activate();
Activate();是让主窗口处于激活状态,从而避免了进入最小化。
如果觉得《c# WPF 程序窗口根据电脑屏幕的不同尺寸自动切换大小 主窗口显示问题》对你有帮助,请点赞、收藏,并留下你的观点哦!