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.





XAML Code


<Window x:Class="sample_wpf.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:y="clr-namespace:sample_wpf"
        Title="TestWindow" Height="177" Width="378">
    <Window.Resources>
        <y:ColorConverter x:Key="changecolor"/>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="80"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>
    <StackPanel>
        <ComboBox Width="200" Height="30" Name="lst">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                     <TextBlock Text="{Binding value}" Foreground="{Binding value, Converter=                                 {StaticResource changecolor}}" Width="117"></TextBlock>
                </DataTemplate>
                </ComboBox.ItemTemplate>
        </ComboBox>
    </StackPanel>
    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Center">
        <Button Click="Button_Click" Name="val" Width="150" Height="30">Fetch</Button>
    </StackPanel>
    </Grid>
</Window>

 C# Code

    public partial class MainWindow : Window
    {
     
        public MainWindow()
        {
            InitializeComponent();          
      
        }

        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;
            else
                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";
            else
                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.