.net - Databinding an enum property to a ComboBox in WPF -
as example take following code:
public enum exampleenum { foobar, barfoo } public class exampleclass : inotifypropertychanged { private exampleenum example; public exampleenum exampleproperty { { return example; } { /* set , notify */; } } }
i want databind property exampleproperty combobox, shows options "foobar" , "barfoo" , works in mode twoway. optimally want combobox definition this:
<combobox itemssource="what goes here?" selecteditem="{binding path=exampleproperty}" />
currently have handlers combobox.selectionchanged , exampleclass.propertychanged events installed in window binding manually.
is there better or kind of canonical way? use converters , how populate combobox right values? don't want started i18n right now.
edit
so 1 question answered: how populate combobox right values.
retrieve enum values list of strings via objectdataprovider static enum.getvalues method:
<window.resources> <objectdataprovider methodname="getvalues" objecttype="{x:type sys:enum}" x:key="exampleenumvalues"> <objectdataprovider.methodparameters> <x:type typename="exampleenum" /> </objectdataprovider.methodparameters> </objectdataprovider> </window.resources>
this can use itemssource combobox:
<combobox itemssource="{binding source={staticresource exampleenumvalues}}"/>
you can create custom markup extension.
example of usage:
enum status { [description("available.")] available, [description("not here right now.")] away, [description("i don't have time right now.")] busy }
<combobox itemssource="{binding source={my:enumeration {x:type my:status}}}" displaymemberpath="description" selectedvalue="{binding currentstatus}" selectedvaluepath="value" />
and implementation...
public class enumerationextension : markupextension { private type _enumtype; public enumerationextension(type enumtype) { if (enumtype == null) throw new argumentnullexception("enumtype"); enumtype = enumtype; } public type enumtype { { return _enumtype; } private set { if (_enumtype == value) return; var enumtype = nullable.getunderlyingtype(value) ?? value; if (enumtype.isenum == false) throw new argumentexception("type must enum."); _enumtype = value; } } public override object providevalue(iserviceprovider serviceprovider) { var enumvalues = enum.getvalues(enumtype); return ( object enumvalue in enumvalues select new enumerationmember{ value = enumvalue, description = getdescription(enumvalue) }).toarray(); } private string getdescription(object enumvalue) { var descriptionattribute = enumtype .getfield(enumvalue.tostring()) .getcustomattributes(typeof (descriptionattribute), false) .firstordefault() descriptionattribute; return descriptionattribute != null ? descriptionattribute.description : enumvalue.tostring(); } public class enumerationmember { public string description { get; set; } public object value { get; set; } } }
Comments
Post a Comment