Tuesday, 6 August 2013

WPF - IValueConverter

           Whenever we need to bind a value with one control , Almost all the time we would not get the same type of input what we expect, So we need an interface which will convert the input in to our required format.In WPF we have a interface like that "IValueConverter which  will convert the user input value when binding to the target and as well as we can convert them back to source.

         The IValueConverter implements the two methods Convert and ConvertBack.. Both Convert and ConvertBack are taken the culture parameters to indicates the CultureInfo.


<Window x:Class="sample_wpf.MainWindow"
        Title="TestWindow" Height="177" Width="378">
        <y:ColorConverter x:Key="changecolor"/>
            <RowDefinition Height="80"/>
            <RowDefinition Height="40"/>
        <ComboBox Width="200" Height="30" Name="lst">
                     <TextBlock Text="{Binding value}" Foreground="{Binding value, Converter=                                 {StaticResource changecolor}}" Width="117"></TextBlock>
    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center">
        <Button Click="Button_Click" Name="val" Width="150" Height="30">Fetch</Button>

 C# Code

    public partial class MainWindow : Window
        public MainWindow()

        private void Button_Click(object sender, RoutedEventArgs e)
            ObservableCollection<BindingData> data = new ObservableCollection<BindingData>();
            data.Add(new BindingData() {  value="Red"   });
            data.Add(new BindingData() { value = "blue" });
            data.Add(new BindingData() { value = "green" });
            lst.ItemsSource = data;

    class BindingData
        public string  value { set; get; }

    class ColorConverter:IValueConverter

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            if (value == "Red")
                return Brushes.Red;
            if (value == "blue")
                return Brushes.Blue;
                return Brushes.Green;

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
              if ((value as SolidColorBrush) == Brushes.Red)
                return "Red";
            else if ((value as SolidColorBrush) == Brushes.Blue)
                return "blue";
                return "green"; 

Once you have created a converter, you can add it as a resource in your Extensible Application Markup Language (XAML) . ColorConverter Changes the color of the foreground of combobox items based on there values bind to it.

Click on the Fetch button once the screen is loaded, to bind the data with combobox.

From this you can learn the basics of IValueConverter and there usage.