Binding Enums values to Combo Box

Goldytech
Posted by Goldytech under Silverlight category on | Views : 4885
Sometimes it is more advisable to bind the combo box items to Enum rather than from tables, when we know the options will be limited and we do not want to use ComboxItems in xaml.

Suppose you have this enum

public enum Databases
{
SQLServer,
Oracle,
MySQL
}


Now here is the Xaml code for combo box binding

<Window x:Class="BindToEnum.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="BindToEnum"
xmlns:local="clr-namespace:BindToEnum"
xmlns:sys="clr-namespace:System;assembly=mscorlib"
SizeToContent="WidthAndHeight"
>
<Window.Resources>
<ObjectDataProvider MethodName="GetValues" ObjectType="{x:Type sys:Enum}" x:Key="odp">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="local:Databases"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>

<Border Margin="30" BorderBrush="Blue" BorderThickness="2" Padding="10">
<StackPanel>
<Label>Select the database of your choice:</Label>
<ComboBox ItemsSource="{Binding Source={StaticResource odp}}" IsSynchronizedWithCurrentItem="true"/>
</StackPanel>
</Border>
</Window>

Comments or Responses

Login to post response