Friday 10 April 2015

StringToColorConverter for Xamarin.Forms

You may have a requirement to bind a string property to a Color property, such as TextColor. If this is the case then you will need to create a converter to perform the conversion from string to Color. The following is a sample of such a converter :-

Firstly, the converter :-

using System;
using System.Globalization;
using Xamarin.Forms;
namespace LabelTextColorSample
{
    public class StringToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string valueAsString = value.ToString();
            switch (valueAsString)
            {
                case (""):
                    {
                        return Color.Default;
                    }
                case ("Accent"):
                    {
                        return Color.Accent;
                    }
                default:
                    {
                        return Color.FromHex(value.ToString());
                    }
            }
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return null;
        }
    }
}

Then the XAML which consumes it :-


    
        
            
        
    
    
Then the setting of the BindingContext :-

using Xamarin.Forms;
namespace LabelTextColorSample
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            this.BindingContext = MyViewModel.Instance;
        }
    }
}

And finally the ViewModel :-

namespace LabelTextColorSample
{
    public class MyViewModel
    {
        private static MyViewModel _instance;
        public static MyViewModel Instance
        {
            get { return _instance ?? (_instance = new MyViewModel()); }
        }
        public string MyTextColor
        {
            get { return "#00FF00"; }
        }
    }
}

Hope this is helpful.

4 comments: