WPF 用户控件设计时间大小
在 WPF 中创建 UserControl 时,我发现给它一些任意的高度和宽度值很方便,以便我可以在 Visual Studio 设计器中查看我的更改.但是,当我运行控件时,我希望 Height 和 Width 是未定义的,以便控件将扩展以填充我放置它的任何容器. 如何在不必删除 Height 和 Width 值之前实现相同的功能建立我的控制?(或者在父容器中不使用 DockPanel.)
When creating a UserControl in WPF, I find it convenient to give it some arbitrary Height and Width values so that I can view my changes in the Visual Studio designer. When I run the control, however, I want the Height and Width to be undefined, so that the control will expand to fill whatever container I place it in. How can I acheive this same functionality without having to remove the Height and Width values before building my control? (Or without using DockPanel in the parent container.)
下面的代码演示了这个问题:
The following code demonstrates the problem:
<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
的以下定义在设计时显示合理,但在运行时显示为固定大小:
The following definition of UserControl1
displays reasonably at design time but displays as a fixed size at run time:
<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
:
The following definition of UserControl1
displays as a dot at design time but expands to fill the parent Window1
at run time:
<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>
在 Visual Studio 中将 Width 和 Height 属性添加到您的 UserControl XAML,但在代码隐藏中插入此
In Visual Studio add the Width and Height attribute to your UserControl XAML, but in the code-behind insert this
public UserControl1()
{
InitializeComponent();
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
this.Width = double.NaN; ;
this.Height = double.NaN; ;
}
}
这会检查控件是否在设计模式下运行.如果不是(即运行时),它会将 Width 和 Height 设置为 NaN(不是数字),这是您在 XAML 中删除 Width 和 Height 属性时设置的值.
This checks to see if the control is running in Design-mode. If not (i.e. runtime) it will set the Width and Height to NaN (Not a number) which is the value you set it to if you remove the Width and Height attributes in XAML.
因此,在设计时,您将拥有预设的宽度和高度(包括您是否将用户控件放入表单中),并且在运行时它将根据其父容器停靠.
So at design-time you will have the preset width and height (including if you put the user control in a form) and at runtime it will dock depending on its parent container.
希望有所帮助.