WPF UserControl Design Time Size

2020-01-27 11:44发布

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>

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>

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>

9条回答
时光不老,我们不散
2楼-- · 2020-01-27 12:19

Some have suggested using the LicenseManager.UsageMode property which I've never seen before but I have used the following code.

if(!DesignerProperties.GetIsInDesignMode(this))
{
    this.Width = double.NaN;
    this.Height = double.NaN;
}

esskar,

I just want to add that you should generally always call the method of the base when overriding an "On" method.

protected override void OnVisualParentChanged(DependencyObject oldParent)
{
    base.OnVisualParentChanged(oldParent);

    ...
}

Great workaround by the way, I'm using it myself now too.

查看更多
兄弟一词,经得起流年.
3楼-- · 2020-01-27 12:21

Use MinWidth and MinHeight on the control. That way, you'll see it in the designer, and at runtime it will size the way you want.

查看更多
男人必须洒脱
4楼-- · 2020-01-27 12:21

I do it similar, but my solution assures that if you add your control to an container in design mode, it will appear reasonably.

protected override void OnVisualParentChanged(DependencyObject oldParent)
{
    if (this.Parent != null)
    {
       this.Width = double.NaN;
       this.Height = double.NaN;
    }
}

what do you think?

查看更多
登录 后发表回答