Skip to content

Instantly share code, notes, and snippets.

@dansiegel
Created August 18, 2020 18:59
Show Gist options
  • Save dansiegel/e0643c9630f96cd8d697ad429d7988d2 to your computer and use it in GitHub Desktop.
Save dansiegel/e0643c9630f96cd8d697ad429d7988d2 to your computer and use it in GitHub Desktop.
Binding Enums in Xamarin.Forms
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace AwesomeApp.Xaml
{
[ContentProperty(nameof(Type))]
public class EnumBindingSourceExtension : IMarkupExtension
{
public Type Type { get; set; }
public object ProvideValue(IServiceProvider serviceProvider)
{
if (Type is null || !Type.IsEnum)
throw new Exception("You must provide a valid enum type");
return Enum.GetValues(Type);
}
}
}
namespace AwesomeApp
{
public enum Status
{
Good,
Bad,
SoSo
}
}
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:xaml="clr-namespace:AwesomeApp.Xaml"
xmlns:local="clr-namespace:AwesomeApp"
x:Class="AwesomeApp.Views.ViewA">
<StackLayout VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand">
<Picker ItemsSource="{xaml:EnumBindingSource {x:Type local:Status}}" />
</StackLayout>
</ContentPage>
@kerberosargos
Copy link

OK sorry for asked you. I forgot. You do not help to people.

@dansiegel
Copy link
Author

@kerbooo I help lots of people... this is a 101 problem... I might take the time to explain it but you're not a client or a sponsor, and at this point you just pissed me off with an entitled attitude.

@kerberosargos
Copy link

Hey you are not a GOD. Just a human. OK don't help me or don't help any people which they are not sponsor to you and I have been sponsor for you in past. I do not believe you for helping people. I regret that I asked you for help. Sorry.

@dansiegel
Copy link
Author

I don't pretend to be a "GOD"... but I also don't owe you anything. I've already answered your question I'm not obligated to give you the full code you want or need. I suggest you look at my answer again and then go look at some docs for Xamarin.Forms.

@kerberosargos
Copy link

Yes you are right, you do not have do anything for me or any other people. But I think you don't know real mean of "help". Have nice day.

@jon-peel
Copy link

Hey @dansiegel, I am working on an app and trying to reduce the number of strings being moved around.

This example was exactly what I was looking for, and worked 100% as I expected.
Thank you very much. 🙂

Copy link

ghost commented Jan 31, 2022

Thanks a lot for this @dansiegel! exactly what I needed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment