在WPF中创建UserControl时,我发现给它一些任意的Height和Width值很方便,这样我就可以在Visual Studio设计器中查看我的更改。但是当我运行控件时,我希望Height和Width是未定义的,这样控件将扩展以填充我放置它的任何容器。如何在不必在构建控件之前删除Height和Width值的情况下实现相同的功能?(或者不使用父容器中的DockPanel)
以下代码演示了问题:
<Window x:Class="ExampleApplication3.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:loc="clr-namespace:ExampleApplication3"
Title="Example" Height="600" Width="600">
<Grid Background="LightGray">
<loc:UserControl1 />
</Grid>
</Window>
以下是UserControl1
的定义,设计时可以正常显示,但运行时大小固定:<UserControl x:Class="ExampleApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300" Width="300">
<Grid Background="LightCyan" />
</UserControl>
UserControl1
的下面定义在设计时显示为一个点,但在运行时会展开以填充父级Window1
:
<UserControl x:Class="ExampleApplication3.UserControl1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Grid Background="LightCyan" />
</UserControl>