设置SizeToContent
到WidthAndHeight
应该工作。请注意,SizeToContent
属性会自动设置为Manual
,如果用户使用调整大小手柄或拖动边框来调整窗口大小,那么您可能还想将ResizeMode
属性设置为NoResize
。
请参考其在3秒后设定ContentPresenter
的一个为500x300矩形的Content
属性以下示例代码:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
Title="MainWindow"
SizeToContent="WidthAndHeight"
ResizeMode="NoResize">
<Grid>
<ContentPresenter x:Name="cc" Focusable="true" Margin="0">
<ContentPresenter.Content>
<TextBlock>test</TextBlock>
</ContentPresenter.Content>
</ContentPresenter>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
Loaded += async (s, e) =>
{
await Task.Delay(3000);
cc.Content = new Rectangle { Width = 500, Height = 300, Fill = Brushes.Red };
};
}
}
窗口的大小,然后增加,正如预期。
来源
2017-04-19 14:38:03
mm8
感谢您的回复。我试过了,但没有奏效。 – Progstar
那么你显然做错了什么,因为它为我创造奇迹。 “不起作用”究竟意味着什么? – mm8
看起来像窗口是空的内容打开(如窗口宽度和高度等于0)。但内容肯定存在。 – Progstar