如何从XAML获取屏幕尺寸?

14

我正在使用C#上的WPF来设计GUI,并且我想从XAML代码中获取屏幕大小(宽度和高度的值)。

我知道如何在C#代码中获取它们,如下:

   Width = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Width;
   Height = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Height;

但我不知道如何从 XAML 代码中获取它们。

3个回答

24

这将起作用。 你可以在这里阅读更多有关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>

10

2

假设您在XAML中的父容器为Grid,并将其命名为grdForm。

在代码后台,可以通过以下方式获取其尺寸:

double width = grdForm.ActualWidth

double height = grdForm.ActualHeight


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接