WPF UserControl设计时间大小

Jos*_*ant 51 wpf user-controls autosize

在WPF中创建UserControl时,我发现给它一些任意的Height和Width值很方便,这样我就可以在Visual Studio设计器中查看我的更改.但是,当我运行控件时,我希望高度和宽度未定义,以便控件将展开以填充我放入的任何容器.如何在不必删除高度和宽度值之前实现相同的功能建立我的控制?(或者不在父容器中使用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>
Run Code Online (Sandbox Code Playgroud)

以下定义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>
Run Code Online (Sandbox Code Playgroud)

以下定义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>
Run Code Online (Sandbox Code Playgroud)

Bri*_*ahy 79

对于Blend,一个鲜为人知的技巧是将这些属性添加到您的usercontrol或窗口:

 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
mc:Ignorable="d"
       d:DesignHeight="500" d:DesignWidth="600"
Run Code Online (Sandbox Code Playgroud)

这将设计高度和宽度分别设置为500和600.但是这只适用于混合设计师.不是Visual Studio Designer.

就Visual Studio Designer而言,您的技术是可行的.这就是我不使用Visual Studio Designer的原因.;)

  • 这不再是一招.VS2012将为新的空UserControl创建完全解决方案! (6认同)

Ale*_*eby 38

在Visual Studio中,将"宽度"和"高度"属性添加到UserControl XAML,但在代码隐藏中插入此属性

public UserControl1()
{
    InitializeComponent();
    if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
    {
        this.Width = double.NaN; ;
        this.Height = double.NaN; ;
    }
}
Run Code Online (Sandbox Code Playgroud)

这将检查控件是否在设计模式下运行.如果不是(即运行时),则将宽度和高度设置为NaN(非数字),如果删除XAML中的"宽度"和"高度"属性,则将其设置为值.

因此,在设计时,您将拥有预设的宽度和高度(包括将用户控件放在表单中),并且在运行时它将根据其父容器进行停靠.

希望有所帮助.


CLa*_*RGe 8

以下是Silverlight Designer中的设计时属性列表.它们与WPF设计者相同.

它列出了所有的d:值在设计可用,例如d:DesignHeight,d:DesignWidth,d:IsDesignTimeCreatable,d:CreateList和其他几个人.


小智 6

我一直这样做.只需将宽度和高度值设置为"auto",即可实例化控件,这将覆盖该UserControl的设计时值.

即: <loc:UserControl1 Width="auto" Height="auto" />

另一种选择是将MinWidth和MinHeight的组合设置为允许设计时工作的大小,而宽度和高度保持"自动".显然,只有在运行时不需要UserControl的大小小于最小值时,这才有效.