Tuesday, 28 February 2012

IMultiValueConverter In Silverlight:-

Silverlight does not support IMultiValueConverter.There may be scenorios like binding the label with FullName using FirstName and LastName propertys.So we can achieve this using Dependency Propertys.

->Create a User class.

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

        public string LastName { get; set; }

->Create a MyLabel class and inherit from Label class.

 public class MyLabel : Label
        //Full name property.
        public string FullName
                return (string)GetValue(FullNameProperty);
                SetValue(FullNameProperty, value);


        //Dependency property for fullname.
        public static readonly DependencyProperty FullNameProperty = DependencyProperty.Register("FullName", typeof(string), typeof(MyLabel), null);

        public MyLabel()
            //Adding load event.
            Loaded += new RoutedEventHandler(MyLabel_Loaded);

        //Load event.
        void MyLabel_Loaded(object sender, RoutedEventArgs e)
            //Add the fullname and lastname.
            this.Content = FullName + this.Content;

->Add the MyLabel control in xaml for FullName.

<UserControl x:Class="SilverlightIMultiValueConverter.MainPage"
    d:DesignHeight="300" d:DesignWidth="400" Loaded="UserControl_Loaded"

    <Grid x:Name="LayoutRoot" Background="White">
        <ListBox Name="lstUsers">
                            <ColumnDefinition Width="50"></ColumnDefinition>
                            <ColumnDefinition Width="50"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                        <TextBlock Grid.Column="0" Text="{Binding Path=FirstName}"></TextBlock>
                        <TextBlock Grid.Column="1" Text="{Binding Path=LastName}"></TextBlock>
                        <dep:MyLabel Grid.Column="2" FullName="{Binding FirstName}" Content="{Binding Path=LastName}"></dep:MyLabel>

->In user control load event bind the listbox.
        private void UserControl_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 = "ANDRA", LastName = "Jackson”});

            //Set the itemsource 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