wpf Window Height="Auto" 未按预期工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/812079/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 20:20:45  来源:igfitidea点击:

Window Height="Auto" not working as expected

wpf

提问by Nikos Tsokos

What I am trying to do is show a window, that does not explicitly have a height/width, (both values omitted or set to Auto). I was guessing that the window would find out its size by auto - calculating all contained usercontrols sizes, but this doesn't actually work!

我想要做的是显示一个没有明确具有高度/宽度的窗口(两个值都省略或设置为Auto)。我猜测窗口会通过自动计算所有包含的用户控件大小来找出它的大小,但这实际上不起作用!

Instead I get a big window with Actualwidthand Actualheightvalues both set to 512 (?!?!)

相反,我得到了一个大窗口,Actualwidth并且Actualheight值都设置为 512 (?!?!)

Window declaration:

窗口声明:

<Window x:Class="Window3"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Window3" 
  Height="Auto">
<StackPanel>
    <Label>Window</Label>
</StackPanel>
</Window>

Showing this window as a dialog via:

通过以下方式将此窗口显示为对话框:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click
    Dim dlg As New Window3
    dlg.ShowDialog()
End Sub

Is there a solution for this? I don't want to explicitly set the size of my window because many controls in the form will be collapsed based on constructor parameters, and trying to find the actual size of the form would be tricky (and ugly).

有解决方案吗?我不想显式设置窗口的大小,因为表单中的许多控件将根据构造函数参数折叠,并且试图找到表单的实际大小会很棘手(而且很难看)。

回答by Muad'Dib

Set the window's property SizeToContent="WidthAndHeight". This should help.

设置窗口的属性SizeToContent="WidthAndHeight"。这应该有帮助。

回答by Vishal

Old question but an updated answer:

老问题,但更新的答案:

As @Muad'Dib suggested in his answer :

正如@Muad'Dib 在他的回答中所建议的那样:

you should set SizeToContent="WidthAndHeight".

你应该设置SizeToContent="WidthAndHeight".

If the size of content of window increases more than the screen size, window can overflow from screen. So, you must consider:

如果窗口内容的大小增加超过屏幕大小,窗口可能会从屏幕溢出。所以,你必须考虑:

MaxWidth="600"
MaxHeight="400"

回答by Feelbad Soussi Wolfgun DZ

Well you can't set the window height to auto, to do this you can use a little trick, name the main main grid container, set its height to auto then bind the window height to the height of the main grid

那么你不能将窗口高度设置为自动,为此你可以使用一个小技巧,命名主网格容器,将其高度设置为自动,然后将窗口高度绑定到主网格的高度

回答by Hooman

Set size in curent screen with loaded event windows

在加载事件窗口的当前屏幕中设置大小