יום חמישי, 7 באפריל 2011

WPF Data Binding Converter


Following Post explains how to create Converter for WPF data binding.
For example we need to bind Lable control to his Background propertie:


 <Label.Background>
                    <Binding Path="BranchColor">...

but in Data Source we are getting string instead of Color: Red, Blue, Green and so...

We need to create converter that will possible to convert string "colors" to System.Windows.Model class.

We need to perform following steps:



1. Write Converter class with converts and Converts back methods:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Media;
using System.Drawing;

namespace GarageManager.Converters
{  
    [ValueConversion(typeof(decimal), typeof(string))]
    public class BrushesConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;
            BrushConverter convertor = new BrushConverter();
            return convertor.ConvertFromString(value.ToString());
        }
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;
            BrushConverter convertor = new BrushConverter();
            return convertor.ConvertToString(value);
        }
    }
}

2. Register it on our XML file where we writing data binding:

xmlns:local="clr-namespace:GarageManager.Converters"

3. and perform data biding with converter:

 <Label x:Name="lblBranchColor"  Grid.Column="0" Grid.RowSpan="3" Width="5">
                <Label.Background>
                    <Binding Path="BranchColor">
                        <Binding.Converter>
                            <local:BrushesConverter></local:BrushesConverter>
                        </Binding.Converter>
                    </Binding>
                </Label.Background>
            </Label>

Hope it's HELPS,
Thanks,
Alex.

אין תגובות:

הוסף רשומת תגובה