-->

WPF designer custom properties - dropdown

2019-09-16 01:49发布

问题:

I would like to have a drop down selection for a custom property on a User Control in WPF. Everything works fine when I use an Enum as the property:

/// <summary>
/// Interaction logic for Sample.xaml
/// </summary>
public partial class Sample : System.Windows.Controls.UserControl
{
    public Sample()
    {
        InitializeComponent();
    }

    [DefaultValue(Letters.A)]
    [Browsable(true)]
    [Category("ControlDisplay")]
    [Description("Letter")]
    public Letters Letter { get; set; }


    public enum Letters
    {
        A,
        B,
        C,
        D
    }
}

Awesome :).

But I want to achieve this for a custom class or even a string. How Should I do it?

Thanks in advance.

回答1:

Finally got the anwser (after digging some documentation - a lot of it). First of all there is the Type Converter atribute then a nice walktrought how to implement it is here. This is what led me to it.

In a nutshell: Implement a type converter GetStandardValuesSupported(ITypeDescriptorContext context) to return true and GetStandardValues(ITypeDescriptorContext context) to return the StandardValuesCollection for the property type. Finally just decorate the property like so:

    [TypeConverter(typeof(MyClassConverter))]
    public MyClass MyProperty { get; set; }

The designer property window will now have a dropdown with valid values.