Search code examples
c#devexpressdevexpress-windows-ui

WinForm TokenEdit control with bitwise Enum ([Flags])


How to use a DevExpress TokenEdit Control with a bitwise enum?

(I was unable to find any comprehensive short documentation on this case. A bit here and some there.)


Solution

  • Let's define the enum

    [Flags]
    public enum BeverageInfoEnum
    {
        Water       = 1 << 0,
        HasAlcool   = 1 << 1,
        Wine        = 1 << 2, 
        Soda        = 1 << 3, 
        Warm        = 1 << 4
    }
    

    The [Flags] attribute is mandatory here. Values can be mixed.

    The DevExpress TokenEdit has a new feature (starting 14.2.4) thant handles automatically bitwise enums. Let's say, in your Control/Form you have a DevExpress.XtraEditors.TokenEdit tokenEditInfo, you can simply:

    // can be set in designer mode
    this.tokenEditInfo.Properties.EditValueType = DevExpress.XtraEditors.TokenEditValueType.Enum; 
    
    // this is were the magic happens
    this.tokenEditInfo.Properties.Tokens.AddEnum(typeof(BeverageInfoEnum), true, true);
    

    Then, you can get the value from it (or just use DataBinding on EditValue):

    var b = (BeverageInfoEnum)this.tokenEditInfo.EditValue
    

    You'll have all the bitwise values in b aggregated. As you expected. Same when setting the value:

    var b = BeverageInfoEnum.Water | BeverageInfoEnum.Warm;
    (BeverageInfoEnum)this.tokenEditInfo.EditValue = b;
    

    The TokenEditcontrol will split the bitwise value in two and show the two separated tokens.