Saturday, 31 March 2012

DataTrigger In Wpf:-

While binding we can change the properties of a control based  on the binding property value.

->Create a user class with properties UserName,Address and Role.

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

        public string Address { get; set; }

        public string Role { get; set; }

->Add the DataTrigger.

<Window x:Class="WpfDataTriggers.MainWindow"
        Title="MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
            <!--Add the style for label-->
            <Style TargetType="{x:Type Label}" x:Key="lbStyle">
                    <!--Check the user  rights-->
                    <!--If the user is admin-->
                    <DataTrigger Binding="{Binding Role}" Value="Admin">
                        <Setter Property="Content" Value="You have administration rights."></Setter>
                        <Setter Property="Background" Value="Green"></Setter>
                    <!--If the user is guest-->
                    <DataTrigger Binding="{Binding Role}" Value="Guest">
                        <Setter Property="Content" Value="You dont' have administration rights."></Setter>
                        <Setter Property="Background" Value="Red"></Setter>
        <ListBox Name="lstUsers">
                    <Grid >
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="100"></ColumnDefinition>
                            <ColumnDefinition Width="200"></ColumnDefinition>
                        <!--Bind the user name-->
                        <Label Grid.Column="0" Content="{Binding UserName}"></Label>

                        <!--Bind the address-->
                        <Label Grid.Column="1" Content="{Binding Address}"></Label>

                        <!--Apply the style resource for label-->
                        <Label Grid.Column="2" Style="{StaticResource lbStyle}"></Label>

->Bind the listbox in the window load event.

private void Window_Loaded(object sender, RoutedEventArgs e)
            //User list
            List<User> lstUser = new List<User>();

            //Adding users.
            lstUser.Add(new User() { UserName = "David", Address = "Mumbai", Role = "Admin" });
            lstUser.Add(new User() { UserName = "Anderson", Address = "Pune", Role = "Guest" });
            lstUser.Add(new User() { UserName = "Andri", Address = "Mumbai", Role = "Admin" });

            //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