Posted by: Zeeshan Amjad | December 13, 2011

Value Converter and Markup Extension


We saw an example of Multivalue converter markup extension here. Here we created a class inherited by MarkupExtension base class and implement IMultiValueConverter interface. In fact we can go one step ahead and implement both IValueConverter and IMultiValueConverter in our class so it can be used with Binding as well as Multi Binding. Here is our class.

Code Snippet
[ValueConversion(typeof(String), typeof(String))]
public class StudentNameExtension : MarkupExtension,
    IMultiValueConverter,
    IValueConverter
{
    public StudentNameExtension()
    {

    }

    #region MarkupExtension
    
    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }

    #endregion

    #region IMultiValueConverter

    public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
    {
        string firstName = values[0] as string;
        string lastName = values[1] as string;

        return string.Format("{0}, {1}", lastName, firstName);
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion

    #region IValueConverter
    
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Student student = value as Student;

        if (student != null)
        {
            return string.Format("{0}, {1}", student.LastName, student.FirstName);
        }
        else
        {
            return string.Empty;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    #endregion
}

 

The usage of this class is also very simple. Here is the usage of both converter in binding and multi binding.

Code Snippet
<TextBlock Margin="5">
    <TextBlock.Text>
        <MultiBinding Converter="{local:StudentName}">
            <Binding Path="FirstName"/>
            <Binding Path="LastName"/>
                            </MultiBinding>
    </TextBlock.Text>
</TextBlock>
<TextBlock Margin="5" Text="{Binding Converter={local:StudentName}}" />

 

Here is complete C# code of the program.

Code Snippet
using System;
using System.Globalization;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;

namespace WpfMultiValue
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            Student student = new Student() { FirstName = "Bob", LastName = "Smith" };

            DataContext = student;
        }
    }

    public class Student
    {
        public string FirstName
        { get; set; }

        public string LastName
        { get; set; }
    }
    
    [ValueConversion(typeof(String), typeof(String))]
    public class StudentNameExtension : MarkupExtension,
        IMultiValueConverter,
        IValueConverter
    {
        public StudentNameExtension()
        {

        }

        #region MarkupExtension
        
        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return this;
        }

        #endregion

        #region IMultiValueConverter

        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {
            string firstName = values[0] as string;
            string lastName = values[1] as string;

            return string.Format("{0}, {1}", lastName, firstName);
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region IValueConverter
        
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            Student student = value as Student;

            if (student != null)
            {
                return string.Format("{0}, {1}", student.LastName, student.FirstName);
            }
            else
            {
                return string.Empty;
            }
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

 

And here is complete XAML code of the program.

Code Snippet
<Window x:Class="WpfMultiValue.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
        xmlns:local="clr-namespace:WpfMultiValue"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        <TextBlock Margin="5">
            <TextBlock.Text>
                <MultiBinding Converter="{local:StudentName}">
                    <Binding Path="FirstName"/>
                    <Binding Path="LastName"/>
                                    </MultiBinding>
            </TextBlock.Text>
        </TextBlock>
        <TextBlock Margin="5" Text="{Binding Converter={local:StudentName}}" />
    </StackPanel>
</Window>

 

Here is the output of the program.

BindingMultiBinding

Advertisements

Responses

  1. […] few example of Value converter. Lets take a look at one example of IMultiValueConverter we discuss here. Here is our code. Code Snippet #region […]


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 )

Google+ photo

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

Connecting to %s

Categories

%d bloggers like this: