gpt4 book ai didi

c# - 获取 Window WPF 的高度/宽度

转载 作者:太空狗 更新时间:2023-10-29 17:31:41 24 4
gpt4 key购买 nike

我有以下代码

<Window x:Class="Netspot.DigitalSignage.Client.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" WindowStyle="SingleBorderWindow"
WindowStartupLocation="CenterScreen"
WindowState="Normal" Closing="Window_Closing">

任何获取高度/宽度的尝试都会返回 NaN 或 0.0

谁能告诉我获取方法?

这2个方法都不行

//Method1
var h = ((System.Windows.Controls.Panel)Application.Current.MainWindow.Content).ActualHeight;
var w = ((System.Windows.Controls.Panel)Application.Current.MainWindow.Content).ActualWidth;

//Method2
double dWidth = -1;
double dHeight = -1;
FrameworkElement pnlClient = this.Content as FrameworkElement;
if (pnlClient != null)
{
dWidth = pnlClient.ActualWidth;
dHeight = pnlClient.ActualWidth;
}

应用程序不会全屏运行。

最佳答案

1.) 在后面的代码中订阅窗口调整大小事件:

this.SizeChanged += OnWindowSizeChanged;

2.) 使用 SizeChangedEventArgs 对象 'e' 获取您需要的尺寸:

protected void OnWindowSizeChanged(object sender, SizeChangedEventArgs e)
{
double newWindowHeight = e.NewSize.Height;
double newWindowWidth = e.NewSize.Width;
double prevWindowHeight = e.PreviousSize.Height;
double prevWindowWidth = e.PreviousSize.Width;
}

请记住这是非常普遍的情况,您可能(也可能不是)必须进行一些检查以确保您的大小值为 0。

我用它来随着主窗口的变化动态调整列表框的大小。基本上我想要的只是此控件的高度更改与窗口高度更改相同的量,以便其父“面板”在任何窗口更改期间看起来一致。

下面是代码,更具体的例子:

注意 我有一个名为“resizeMode”的私有(private)实例整数,它在 Window 代码后面的构造函数中设置为 0。

这是 OnWindowSizeChanged 事件处理程序:

    protected void OnWindowSizeChanged (object sender, SizeChangedEventArgs e)
{
if (e.PreviousSize.Height != 0)
{
if (e.HeightChanged)
{
double heightChange = e.NewSize.Height - e.PreviousSize.Height;
if (lbxUninspectedPrints.Height + heightChange > 0)
{
lbxUninspectedPrints.Height = lbxUninspectedPrints.Height + heightChange;
}
}
}
prevHeight = e.PreviousSize.Height;
}

关于c# - 获取 Window WPF 的高度/宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11013316/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com