xaml - How to set Enum to ItemsSource WPF -
how can set enum listbox in xaml. in listbox need display description not name/value of enum. , when click button need selected enum passed in method via icommand enum not string. example:
public enum myenum { enumone = 0, [description("enum one")] enumtwo = 1, [description("enum two")] enumtwo = 2, [description("enum three")] }
need bind these enums listbox displaymemberpath of description. , upon selection in listbox, pass in selected enum so:
private void buttondidclick(myenum enum) { }
xaml:
<listbox itemssource="{binding myenum"} /> ?
and know how rest far wiring command button..etc.. help.
from production app
got off while ago , cannot find source
bind displaymememberpath value
public static dictionary<t, string> enumtodictionary<t>() t : struct { type enumtype = typeof(t); // can't use generic type constraints on value types, // have check if (enumtype.basetype != typeof(enum)) throw new argumentexception("t must of type system.enum"); dictionary<t, string> enumdl = new dictionary<t, string>(); foreach (t val in enum.getvalues(enumtype)) { enumdl.add(val, val.tostring()); } return enumdl; }
getdescription method
for want know how read description attribute value. following can converted use enum
or extenstion. found implementation more flexible.
using method, replace val.tostring()
getdescription(val)
.
/// <summary> /// returns value of 'description' attribute; otherwise, returns null. /// </summary> public static string getdescription(object value) { string sresult = null; fieldinfo ofieldinfo = value.gettype().getfield(value.tostring()); if (ofieldinfo != null) { object[] ocustomattributes = ofieldinfo.getcustomattributes(typeof(descriptionattribute), true); if ((ocustomattributes != null) && (ocustomattributes.length > 0)) { sresult = ((descriptionattribute)ocustomattributes[0]).description; } } return sresult; }
Comments
Post a Comment