WPF中窗体最大化问题的解决方法

2020-01-05 09:33:44丽君

步骤:

1、 设置窗体相关属性:WindowStyle="None" AllowsTransparency="True" Background="Transparent" ResizeMode="CanMinimize"

窗体需要支持透明,并将窗体设置为透明;设置ResizeMode,否则最大化时,边框会有影响。

2、 添加窗体最大化/还原代码如下:


double normaltop;
double normalleft;
double normalwidth;
double normalheight;
/// <summary>
/// 最大化/还原处理
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Btn_maximize_Click(object sender, RoutedEventArgs e)
{
 //wpf最大化 全屏显示任务栏处理
 if (this.WindowState == WindowState.Normal)
 {
 normaltop = this.Top;
 normalleft = this.Left;
 normalwidth = this.Width;
 normalheight = this.Height;

 double top = SystemParameters.WorkArea.Top;
 double left = SystemParameters.WorkArea.Left;
 double right = SystemParameters.PrimaryScreenWidth - SystemParameters.WorkArea.Right;
 double bottom = SystemParameters.PrimaryScreenHeight - SystemParameters.WorkArea.Bottom;
 gd_main.Margin = new Thickness(left, top, right, bottom);

 this.WindowState = WindowState.Maximized; 
 }
 else
 {
 this.WindowState = WindowState.Normal;

 //必须先设置为0,在重新设值,若前后值一样,会失效 --拖动任务栏后,还原-始终显示在屏幕最左上方
 this.Top = 0;
 this.Left = 0;
 this.Width = 0;
 this.Height = 0;

 this.Top = normaltop;
 this.Left = normalleft;
 this.Width = normalwidth;
 this.Height = normalheight;

 gd_main.Margin = new Thickness(0);
 }
}

3、添加任务栏变化处理

注意:此节实现仅适用于.Net Framework 4.5及以上。因为4.0及以前的版本中不包含StaticPropertyChanged事件。