我正在使用C#上的WPF来设计GUI,并且我想从XAML代码中获取屏幕大小(宽度和高度的值)。
我知道如何在C#代码中获取它们,如下:
Width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
Height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;
但我不知道如何从 XAML
代码中获取它们。
这将起作用。 你可以在这里阅读更多有关SystemParameters的信息。
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenHeight}}" />
<TextBlock Text="{Binding Source={x:Static SystemParameters.FullPrimaryScreenWidth}}" />
<TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenHeight}}" />
<TextBlock Text="{Binding Source={x:Static SystemParameters.PrimaryScreenWidth}}" />
</StackPanel>
</Window>
请查看SystemParameters类:http://msdn.microsoft.com/de-de/library/system.windows.systemparameters.fullprimaryscreenheight.aspx
您可以像这样使用它:
<Object Attribute="{x:Static SystemParameters.FullPrimaryScreenHeight}"/>
(您也可以使用x:Static标记来查询Windows Forms属性,但是如果您正在开发WPF应用程序,则SystemParameters类可能是更好的选择)
假设您在XAML中的父容器为Grid,并将其命名为grdForm。
在代码后台,可以通过以下方式获取其尺寸:
double width = grdForm.ActualWidth
double height = grdForm.ActualHeight