简体   繁体   中英

How to make a type editable in properties window in visual studio?

For example we have these type

public struct Vector2D
{
    public double X{get; set;}
    public double Y{get; set;}
}

One of my user control has property named Value with type Vector2D

Currently if I look up that property. It will display <namespace>.Vector2D and is not editable. (Note that that property is editable and that is not literally displayed as that)

How to make that property editable via properties window in Visual Studio, just like Point , Size , Padding , etc?

Tries to add BrowsableAttribute , EditorAttribute with no argument, but it doesn't work.

I take it you mean editing the variable through the PropertyGrid control. if so you can call on a custom property editor to edit that specific object. I also recommend overriding the ToString function which a format of your choosing. the PropertyGrid uses that fill in the value to display to the user.

how to implement custom editor:

public struct Vector2D : UITypeEditor
{
    //UITypeEditor Implementation

    //Gets the editor style, (dropdown, value or new window)
    public override UITypeEditorEditStyle GetEditStyle(ITypeDescriptorContext context)
    {
        return UITypeEditorEditStyle.Modal;
    }

    //Gets called when the value has to be edited.
    public override object EditValue(ITypeDescriptorContext context, IServiceProvider provider, object value)
    {
        //Calls a dialog to edit the object in
        EditTypeConfig editor = new EditTypeConfig((TypeConfig)value);
        editor.Text = context.PropertyDescriptor.Name;

        if (editor.ShowDialog() == DialogResult.OK)
            return editor.SelectedObject;
        else
            return (TypeConfig)value;
    }

    //Properties

    [DisplayName("X"), Description("X is something"), Category("Value"), ReadOnly(false)]
    public double X { get; set; }
    [DisplayName("Y"), Description("Y is something"), Category("Value"), ReadOnly(false)]
    public double Y { get; set; }
}

Usage:

public class Sample
{
    [DisplayName("Value"), Description("Value is something"), Category("Vectors"), ReadOnly(false)]
    [Editor(typeof(Vector2D), typeof(UITypeEditor))]
    public Vector2D Value { get; set; } 
//Editor(typeof(Vector2D)) calls a class that handles the the editing of that value
    }

I hope this solves your problem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM