如何将 WPF 窗口大小设置为相对监视器屏幕的 25%

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25426930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 12:23:26  来源:igfitidea点击:

How can I set WPF window size is 25 percent of relative monitor screen

wpfxamlc#-4.0desktop-application

提问by user3188127

I have a WPF window and How can I set WPF window size is 25 percent of relative monitor screen.How can I set these properties.

我有一个 WPF 窗口,如何将 WPF 窗口大小设置为相对监视器屏幕的 25%。如何设置这些属性。

回答by Vyas

In your MainWindow Constructor add

在您的 MainWindow 构造函数中添加

this.Height = (System.Windows.SystemParameters.PrimaryScreenHeight * 0.25);
this.Width = (System.Windows.SystemParameters.PrimaryScreenWidth * 0.25);

Also don't set WindowState="Maximized" in your MainWindows.xaml otherwise it won't work. Hope this helps.

也不要在 MainWindows.xaml 中设置 WindowState="Maximized" 否则它将不起作用。希望这可以帮助。

回答by R. Matveev

Or using xaml bindings

或者使用 xaml 绑定

MainWindow.xaml

主窗口.xaml

<Window x:Class="App.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"
        mc:Ignorable="d"
        Title="Main Window" 
        Height="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}, Converter={StaticResource WindowSizeConverter}, ConverterParameter='0.6'}" 
        Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}, Converter={StaticResource WindowSizeConverter}, ConverterParameter='0.8'}" >

Resources.xaml

资源.xaml

<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:App">
    <local:WindowSizeConverter x:Key="WindowSizeConverter"/>
</ResourceDictionary>

WindowSizeConverter.cs

WindowSizeConverter.cs

using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;

namespace App
{
    public class WindowSizeConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double size = System.Convert.ToDouble(value) * System.Convert.ToDouble(parameter, CultureInfo.InvariantCulture);
            return size.ToString("G0", CultureInfo.InvariantCulture);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => DependencyProperty.UnsetValue;
    }
}