如何设置WPF窗口的宽度等于其标题栏中的内容?

时间:2021-09-25 21:04:19

If I have Window in WPF as follows:

如果我在WPF中有Window,如下所示:

<Window
    Title="Alter Window Width so that the complete title is shown."
    SizeToContent="WidthAndHeight"
    WindowStartupLocation="CenterOwner">

This window will automatically resize to make sure all of its content is visible. But it doesn't do the same for the title, so it's possible that a part of the title will be hidden when the window is shown.

此窗口将自动调整大小以确保其所有内容都可见。但它对标题的作用并不相同,因此当显示窗口时,可能会隐藏标题的一部分。

What can be done to make sure that the width of the window is enough to show the title in the title bar?

可以做些什么来确保窗口的宽度足以在标题栏中显示标题?

1 个解决方案

#1


6  

Add a hidden textblock in to the window:

在窗口中添加隐藏的文本块:

<TextBlock 
   Text="{Binding Path=Title,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" 
   Visibility="Hidden" 
   Height="0" 
   Margin="100 0 0 0">
</TextBlock>

The Margin allows for the windows controls to be pushed out of the way.

边距允许窗口控件被推开。

The Height makes the control take up no vertical space.

高度使控件不占用垂直空间。

The Visiblity is probable not required because of the zero height, but by setting it to hidden will cause it to take up space on the canvas but show nothing.

由于零高度可能不需要Visiblity,但通过将其设置为隐藏将导致它占用画布上的空间但不显示任何内容。

#1


6  

Add a hidden textblock in to the window:

在窗口中添加隐藏的文本块:

<TextBlock 
   Text="{Binding Path=Title,RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=Window}}" 
   Visibility="Hidden" 
   Height="0" 
   Margin="100 0 0 0">
</TextBlock>

The Margin allows for the windows controls to be pushed out of the way.

边距允许窗口控件被推开。

The Height makes the control take up no vertical space.

高度使控件不占用垂直空间。

The Visiblity is probable not required because of the zero height, but by setting it to hidden will cause it to take up space on the canvas but show nothing.

由于零高度可能不需要Visiblity,但通过将其设置为隐藏将导致它占用画布上的空间但不显示任何内容。