Enum Binding ItemsSource in WPF

Source: Internet
Author: User

Enumerates bindings to ItemsSource in WPF.

I. Obtaining an enum data source through ObjectDataProvider

First we define an enum class:

Enum Tableselectedtype
    {
        Selectedone,
        Selectedtwo,
        Selectedthird
    }

The data source is then defined in the resource in XAML.

<UserControl.Resources>
        <objectdataprovider x:key="ODP" methodname="GetNames" objecttype="{x:type system:enum}" > 
            <ObjectDataProvider.MethodParameters>
                <x:type typename="Local:tableselectedtype"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
</UserControl.Resources>

We've written an enum data source here, and his key is the ODP. We bind it to the ItemsSource of the ComboBox and look at it.

<combobox itemssource="{Binding source={staticresource ODP}}"/>

But sometimes, we want to bind an enum, but want to display its corresponding Chinese string. For example, "SelectOne" appears as "first".

Here I use the converter (Converter).

public object Convert (object value, Type targetType, object parameter, CultureInfo culture)       {           string[] Enmus = val UE as string[];           List<string> result=new list<string> ();           foreach (var item in Enmus)           {               switch (item)               {case                   "Selectedone":                      result. ADD ("first line");                       break;                   Case "Selectedtwo":                       result. Add ("second row");                       break;                   Case "Selectedthird":                       result. Add ("third row");                       break;               }           }           return result;       }

In XAML:

<combobox itemssource= "{Binding source={staticresource ODP}, Converter={staticresource Enumtypetostringconverter }} "/>

Effect:

Second, by dictionary to save the enum, and bound to the ItemsSource

This convenience and high efficiency. We still use the enum type above. We declare a dictionary attribute tableselectedtypecollection, and the initial words to him.

Class Conboboxenum:usercontrol
    {
        Public Conboboxenum ()
        {
            InitializeComponent ();
            tableselectedtypecollection=string> ();
            Tableselectedtypecollection.add (Tableselectedtype.selectedone,"the first article");
            Tableselectedtypecollection.add (Tableselectedtype.selectedtwo,"second article");
            Tableselectedtypecollection.add (Tableselectedtype.selectedthird,"Article III");
            This
        }
        String> tableselectedtypecollection {get; set;}
    }

In XAML, we use Tableselectedtypecollection to bind the ItemsSource of a ComboBox.

<combobox itemssource="{Binding tableselectedtypecollection}" selectedvalue="{Binding Tableselectedtype } "displaymemberpath=" Value "/>  

Here we use value to display its corresponding Chinese characters. SelectedValue to bind its enum type. Because we usually use the type of enum in the background.

The effect is still the same.

Third, through the characteristics (Attribute) to obtain

Using System.ComponentModel under the MS namespace is used here, and description This feature on enumeration elements.

Enum Tableselectedtype    {        [Description ("Select First Row")]        selectedone,        [Description ("select second Row")]        Selectedtwo,        [Description ("select third Row")]        Selectedthird    }  

We write a enumhelper to get it.

 PublicStaticClass Enumhelper {PublicStatic T getenumattribute<t> (Enum source)where T:attribute {type type = source. GetType (); var sourceName = enum.getname (type, source); FieldInfo field = type. GetField (SourceName); object[] attributes = field. GetCustomAttributes (typeof (T), false); foreach (var o in attributes) { if (O is t) return (t) o; return null;} public static string getdescription (Enum source) {var str = Getenumattribute<descriptionattribute > (source); if (str==null) return null; return str. Description; } }

And then when we instantiate this enumeration, we can call it.

String> tableselectedtypedictionary {get; set;} Public conboboxenum ()        {            InitializeComponent ();            tableselectedtypedictionary=string> ();            Tableselectedtypedictionary.add (Tableselectedtype.selectedone, Enumhelper.getdescription ( Tableselectedtype.selectedone));            Tableselectedtypedictionary.add (Tableselectedtype.selectedtwo, Enumhelper.getdescription ( Tableselectedtype.selectedtwo));            Tableselectedtypedictionary.add (Tableselectedtype.selectedthird, Enumhelper.getdescription ( Tableselectedtype.selectedthird));            This ;}  

Enum Binding ItemsSource in WPF

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.