18

在 WinForms 中,Form 有一个 ClientSize 属性(继承自 Control),它返回其客户区域的大小,即标题栏和窗口边框内的区域。

我在 WPF 中没有看到任何类似的东西:没有 ClientSize、ClientWidth、ClientHeight、GetClientSize() 或任何我能想到的可以猜到名称的东西。

如何获取 WPF 窗口的客户端大小?

4

4 回答 4

11

一种方法是获取最顶层的子元素,this.Content转换为它的类型,然后调用.RenderSize它,这会给你它的大小。

<Window x:Class="XML_Reader.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="400" Width="600" WindowStyle="SingleBorderWindow">
    <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    </Grid>
</Window>

((Grid)this.Content).RenderSize.Height
((Grid)this.Content).RenderSize.Width

编辑:

正如特伦特所说,ActualWidth也是ActualHeight可行的解决方案。基本上更容易获得我上面所说的方法。

于 2009-06-05T12:53:34.167 回答
10
var h = ((Panel)Application.Current.MainWindow.Content).ActualHeight;
var w = ((Panel)Application.Current.MainWindow.Content).ActualWidth;
于 2011-11-02T13:43:39.167 回答
2

一种方法是使用下面的代码。XAML:

<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">
    <Canvas>
    </Canvas>
</Window>

C#:

using System.Windows;

using System.IO;
using System.Xml;
using System.Windows.Controls;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            double dWidth = -1;
            double dHeight = -1;
            FrameworkElement pnlClient = this.Content as FrameworkElement;
            if (pnlClient != null)
            {
                dWidth = pnlClient.ActualWidth;
                dHeight = pnlClient.ActualHeight;
            }
        }
    }
}
于 2009-06-05T13:06:17.090 回答
1

我用了一个Gridwith VerticalAlignment=Top。结果,不幸的是 Grid 不再填充父窗口(这是它的默认行为,但 VerticalAligment 属性破坏了它)。

Border我通过在网格周围放置一个空来解决它。此边框填充窗口的完整内容,它与 wpf 窗口具有的默认边框具有相同的尺寸。

为了让 Grid 填充主窗口,我使用了绑定:
<Border BorderThickness="0" x:Name=Main> <Grid VerticalAlignment="Top" Height="{Binding ElementName=Main, Path=ActualHeight}"> ... </Grid> </Border>

于 2019-02-17T09:40:29.737 回答