Saturday, 31 March 2012

IMultiValueConverter In Wpf:-

There may be scenorios like binding the label with FullName using FirstName and LastName propertys.So we can achieve this using  IMultiValueConverter.

->Create a User class.

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

        public string LastName { get; set; }

->Create a MultiConverter class and implement IMultiValueConverter methods.

public class MultiConverter : IMultiValueConverter
        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            //Check the parameter.
            if (parameter.ToString() == "FullName")
                //Return the fullname.
                return values[0] + values[1].ToString();

            return null;

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
            throw new NotImplementedException();

->Add the MultiConverter class in xaml as static resource.
<Window x:Class="WpfIMultiValueConverter.MainWindow"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
        <my:MultiConverter x:Key="multiConverter"></my:MultiConverter>
        <ListBox Name="lstUsers">
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                        <TextBlock Grid.Column="0" Text="{Binding Path=FirstName}"></TextBlock>
                        <TextBlock Grid.Column="1" Text="{Binding Path=LastName}"></TextBlock>
                        <TextBlock Grid.Column="2">

                           <!--We should use MultiBinding to work with IMultiValueConverter-->
                                                                <MultiBinding Converter="{StaticResource multiConverter}" ConverterParameter="FullName">
                                    <Binding Path="FirstName"></Binding>
                                    <Binding Path="LastName"></Binding>

->In window load event bind the listbox.
private void Window_Loaded(object sender, RoutedEventArgs e)

      //User list
      List<User> lstUser = new List<User>();

      //Adding users.
      lstUser.Add(new User() { FirstName = "David", LastName = "Jackson" });
      lstUser.Add(new User() { FirstName = "Anderson", LastName = "Andi" });
      lstUser.Add(new User() { FirstName = "Andri", LastName = "Jackson" });

      //Set the item source here.
      lstUsers.ItemsSource = lstUser;


Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…

No comments:

Post a Comment