WPF UserControl Design Time Size

后端 未结 9 862
[愿得一人]
[愿得一人] 2020-11-30 22:36

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

9条回答
  •  隐瞒了意图╮
    2020-11-30 23:12

    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; ;
        }
    }
    

    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.

    Hope that helps.

提交回复
热议问题