Bind Enum to a WPF ListBox using ObjectDataProvider




In programming languages, Enumeration has a specific role for storing values. The Enum.GetValues() method retrieves an array of the values of the constants in an Enum. Let us see how to use this method and bind an Enumeration to a WPF ListBox using the ObjectDataProvider.

Create a WPF project with the name of WPF_EnumBinding. In the WPF Project, open the MainPage.Xaml.cs and write an enumeration as shown below:

public enum Department
{
IT,
System,
HRD,
Accts,
Transport
}

Since ‘Enum’ is defined in mscorlib assembly, it is referred in the Xaml code shown below. The ObjectDataProvider is used to bind the Enumeration with the Xaml. The namespace under which enumeration i.e. WPF_EnumBinding is declared, is also referred in the Xaml. The Xaml code is as below:

<Window x:Class="WPF_EnumBinding.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:System;assembly=mscorlib"
xmlns:data="clr-namespace:WPF_EnumBinding"
Title="MainWindow" Height="350" Width="525">
<
Window.Resources>
<
ObjectDataProvider MethodName="GetValues"
ObjectType="{x:Type src:Enum}" x:Key="dname">
<
ObjectDataProvider.MethodParameters>
<
x:Type TypeName="data:Department"></x:Type>
</
ObjectDataProvider.MethodParameters>
</
ObjectDataProvider>
</
Window.Resources>
<
Grid>
<
ListBox Height="294" HorizontalAlignment="Left"
Margin="32,17,0,0" Name="lstEnum" VerticalAlignment="Top"
Width="222" DataContext="{Binding Source={StaticResource dname}}"
ItemsSource="{Binding}">
</
ListBox>
</
Grid>
</
Window>

OUTPUT

image



Will you give this article a +1 ? Thanks in advance




About The Author

Mahesh is having 10 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). He also blogs regularly at DotNetCurry.com. Follow him on twitter @maheshdotnet

comments

0 Responses to "Bind Enum to a WPF ListBox using ObjectDataProvider"
 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions