Hello Devz,
I had to write this post about how to do an Enum binding to a ComboBox, because everytime I need it, I’m surprised there is no “out-of-the-box” solution provided in WPF or Xamarin.Forms.
<Window x:Class="EnumBinding.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:EnumBinding" xmlns:sys="clr-namespace:System;assembly=mscorlib" mc:Ignorable="d" Title="MainWindow" Height="350" Width="525"> <Window.Resources> <ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues" ObjectType="{x:Type sys:Enum}"> <ObjectDataProvider.MethodParameters> <x:Type TypeName="local:StatusEnum"/> </ObjectDataProvider.MethodParameters> </ObjectDataProvider> </Window.Resources> <Grid> <ComboBox HorizontalAlignment="Center" VerticalAlignment="Top" MinWidth="150" Margin="50" ItemsSource="{Binding Source={StaticResource dataFromEnum}}"/> </Grid> </Window>
Please notice this line:
xmlns:sys=”clr-namespace:System;assembly=mscorlib”
And the ObjectDataProvider in the Window.Resources.
With a simple Enum called StatusEnum:
public enum StatusEnum { None = 0, Waiting = 1, Running = 2, Success = 3, Warning = 4, Error = 5 }
So this was the classic way to bind an enum to a combobox. But there is a better way to do that! Yes, please have a look at my post: Enum binding in a combobox – the other way.
Happy coding! 🙂
[…] Previous […]
[…] my two previous posts, I was talking about how to bind an enum (the classic way and the other way). But these two have two major issues. First the all the items from the Enum will […]