Search code examples
c#encodingpropertiesuitypeeditor

Property editor for Encoding property


I'm implementing a custom TextBox and would like its new encoding property to be editable in the designer.

Here is the declaration of the property:

    private Encoding tbEnc;
    public Encoding tbEncoding { get { return tbEnc; } set { tbEnc = value; } }

It shows up in the property grid alright but disabled. I had hoped it would work out of the box as Encoding is a standard type, like, say Font, for which the standard editor comes up.

Do I have to build a UITypeEditor and what would be the simplest implementation?


Solution

  • The disabled state on the property means that NET cant find a match for the Type, namely System.Text.Encoding. Since there are other properties there you probably would not want to show (like all the Isxxxxxxx props), a stock/default editor probably would not do what you want anyway.

    One way would be to use a TypeConverter but for something like this, just exposing the property as an enum can be an advantage:

    • You may not want to support all the options available in the NET Type
    • you can use different, perhaps friendlier names/text if desired
    • As an enum NET will use a dropdown so you dont have to write anything

    class newTB : TextBox
    {
        // encoding subset to implement
        public enum NewTBEncoding
        {
            ASCII, UTF8, UTF7
        };
    
        // prop as enum
        private NewTBEncoding tbEnc;
    
        public NewTBEncoding tbEncoding { 
            get { return tbEnc; } 
            set {tbEnc = value; }
        }
    }
    

    You sometimes have to do a conversion from the enum value to the actual underlying Type, but that is often a one time thing you can do in the property setter or simply when used. Result:

    http://i.imgur.com/fVKXbjl.jpg