语法 Height="{Binding SystemParameters.PrimaryScreenHeight}" 提供了线索,但不起作用。 SystemParameters.PrimaryScreenHeight 是静态的,因此您应使用:
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tools="clr-namespace:MyApp.Tools"
Height="{x:Static SystemParameters.PrimaryScreenHeight}"
Width="{x:Static SystemParameters.PrimaryScreenWidth}"
Title="{Binding Path=DisplayName}"
WindowStartupLocation="CenterScreen"
Icon="icon.ico"
>
而且它会适合整个屏幕。然而,您可能更喜欢安装百分比屏幕尺寸,例如90%,在这种情况下,必须使用绑定规范中的转换器修改语法:
<Window x:Class="MyApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tools="clr-namespace:MyApp.Tools"
Height="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}, Converter={tools:RatioConverter}, ConverterParameter='0.9' }"
Width="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}, Converter={tools:RatioConverter}, ConverterParameter='0.9' }"
Title="{Binding Path=DisplayName}"
WindowStartupLocation="CenterScreen"
Icon="icon.ico"
>
其中 RatioConverter 在 MyApp.Tools 命名空间中声明如下:
namespace MyApp.Tools {
[ValueConversion(typeof(string), typeof(string))]
public class RatioConverter : MarkupExtension, IValueConverter
{
private static RatioConverter _instance;
public RatioConverter() { }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{ // do not let the culture default to local to prevent variable outcome re decimal syntax
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)
{ // read only converter...
throw new NotImplementedException();
}
public override object ProvideValue(IServiceProvider serviceProvider)
{
return _instance ?? (_instance = new RatioConverter());
}
}
}
其中转换器的定义应继承自 MarkupExtension,以便直接在根元素中使用,而无需先前声明为资源。