How to set default value to CustomControl inherite

2019-09-05 15:49发布

问题:

I have a CustomControl inherited from a TextBox which is not setting its Width property when place it to a window at design time. the TextBox required a Width of 120 at design time by default.

How can I set my control width to 120 by default?

Solution more correct for development of control, if exist

回答1:

You can try use DefaultInitializer class:

/*
** In your custom control class
*/

using Microsoft.Windows.Design.Features;
// ...

[Feature(typeof(CustomTextBoxDefaults))]
public class CustomTextBox : TextBox
{
    /* ... */
}

/*
** CustomTextBoxDefaults provides default values for designer
*/

using Microsoft.Windows.Design.Model;
// ...

class CustomTextBoxDefaults : DefaultInitializer
{
    public override void InitializeDefaults(ModelItem item)
    {
        item.Properties["Width"].SetValue(120);
        // Setup other properties
    }
}

Note you should add two assemblies to project: Microsoft.Windows.Design.Extensibility and Microsoft.Windows.Design.Interaction

You may also read this thread: http://social.msdn.microsoft.com/Forums/en-US/1ce1184a-7b8c-40d1-ad52-71b2a6c9b3b6/wpf-designertoolbox-default-values?forum=vswpfdesigner