Colour converter based on Status string.


Declare a class and inherit from the IValueConverter
using System; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Ink; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
using System.Windows.Data;

public class StatusColorConverter:IValueConverter 
    {

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            string status = (string)value; 
            if (value == null) 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
            if (string.IsNullOrEmpty(status)) 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
            else if (status.Trim() == "Open") 
            { 
                return new SolidColorBrush(Colors.Orange); 
            } 
            else if (status.Trim() == "Closed") 
            { 
                return new SolidColorBrush(Colors.Green); 
            } 
            else 
            { 
                return new SolidColorBrush(Colors.LightGray); 
            } 
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
        { 
            throw new NotImplementedException(); 
        } 
    }
Using it in XAML, Below are just the main elements for the understanding. The original XAML page will have more declaration
<navigation:Page xmlns:local="clr-namespace:ProjectName.Converters"
           Title="Page Title Here">
    <navigation:Page.Resources>
        <local:StatusColorConverter x:Key="statusColor" />
    </navigation:Page.Resources>
</navigation:Page>
<Grid>
<Border BorderBrush="White" BorderThickness="2" Background="{Binding Path=Status,Converter={StaticResource colorConvert}}" 
CornerRadius="10,10,10,10" Width="200" Height="150">
<TextBlock Text="{Binding Path=StatusText}" />
</Border>
</Grid>

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s