Data Trigger Sample


   
  

<Window x:Class="DataTriggerSample.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:DataTriggerSample"
  Title="DataTriggerSample" Height="300" Width="300">
  <Window.Resources>
    <c:People x:Key="PeopleData"/>
    <Style TargetType="{x:Type ListBoxItem}">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=RelationshipType}" Value="Family">
          <Setter Property="Background" Value="Yellow" />
        </DataTrigger>
        <DataTrigger Binding="{Binding Path=RelationshipType}" Value="Friend">
          <Setter Property="Background" Value="Pink" />
        </DataTrigger>
        <MultiDataTrigger>
          <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding Path=Name}" Value="A" />
            <Condition Binding="{Binding Path=RelationshipType}" Value="Best Friend" />
          </MultiDataTrigger.Conditions>
          <MultiDataTrigger.Setters>
            <Setter Property="Background" Value="LightGreen" />
          </MultiDataTrigger.Setters>
        </MultiDataTrigger>
      </Style.Triggers>
    </Style>

    <DataTemplate DataType="{x:Type c:Person}">
      <Canvas Width="260" Height="20">
        <TextBlock FontSize="12" Width="130" Canvas.Left="0" Text="{Binding Path=Name}"/>
        <TextBlock FontSize="12" Width="130"  Canvas.Left="130" Text="{Binding Path=RelationshipType}"/>
      </Canvas>
    </DataTemplate>
  </Window.Resources>

  <StackPanel>
    <TextBlock FontSize="18" FontWeight="Bold" HorizontalAlignment="Center">Data Trigger Sample</TextBlock>
    <ListBox Width="250" HorizontalAlignment="Center" Background="White" ItemsSource="{Binding Source={StaticResource PeopleData}}"/>
  </StackPanel>

</Window>

//File:Window.xaml.cs

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace DataTriggerSample
{
    public partial class Window1 : System.Windows.Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
    public class Person
    {
        private string _name;
        private string _relationshipType;

        public string Name
        {
            get { return _name; }
            set { _name = value; }
        }

        public string RelationshipType
        {
            get { return _relationshipType; }
            set { _relationshipType = value; }
        }

        public Person(string name, string relationshiptype)
        {
            this._name = name;
            this._relationshipType = relationshiptype;
        }
    }

    public class People : ObservableCollection<Person>
    {
        public People()
        {
            Add(new Person("A", "Friend"));
            Add(new Person("C", "Family"));
            Add(new Person("B", "Friend"));
        }
    }

}

   
    
     


Defines the contents of column headers and cells by using templates.


   
  

<Window x:Class="WpfApplication1.Window1"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:ds="clr-namespace:WpfApplication1">
  <Window.Resources>
    <ObjectDataProvider x:Key="myDateCollectionDataSource" ObjectType="{x:Type ds:myDateCollection}"/>
    <Style x:Key="GridViewColumnHeaderGripper" TargetType="{x:Type Thumb}">
      <Setter Property="Height" Value="{Binding Path=ActualHeight,RelativeSource={RelativeSource TemplatedParent}}"/>
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type Thumb}">
            <Border>
              <Rectangle HorizontalAlignment="Center" Width="1" Fill="Black"/>
            </Border>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>
    <Style x:Key="myControlTemplateStyle" TargetType="{x:Type GridViewColumnHeader}">
      <Setter Property="Template">
        <Setter.Value>
          <ControlTemplate TargetType="{x:Type GridViewColumnHeader}">
            <Grid Background="LightBlue">
              <DockPanel HorizontalAlignment="Center" VerticalAlignment="Center">
                <CheckBox></CheckBox>
                <TextBlock Text="{TemplateBinding Content}" FontSize="16" Foreground="DarkBlue"/>
              </DockPanel>
              <Canvas>
              <Thumb x:Name="PART_HeaderGripper"
                     Style="{StaticResource GridViewColumnHeaderGripper}"
                     Background="Transparent"
                     />
            </Canvas>
            </Grid>
          </ControlTemplate>
        </Setter.Value>
      </Setter>
    </Style>

    <Style x:Key="myHeaderStyle" TargetType="{x:Type GridViewColumnHeader}">
      <Setter Property="Background" Value="LightBlue"/>
    </Style>

    <DataTemplate x:Key="myHeaderTemplate">
      <DockPanel>
        <CheckBox/>
        <TextBlock FontSize="16" Foreground="DarkBlue">
          <TextBlock.Text>
            <Binding/>
          </TextBlock.Text>
        </TextBlock>
      </DockPanel>
    </DataTemplate>

    <DataTemplate x:Key="myCellTemplateDay">
      <DockPanel>
        <TextBlock Foreground="DarkBlue" HorizontalAlignment="Center">
          <TextBlock.Text>
            <Binding Path="Day"/>
          </TextBlock.Text>
        </TextBlock>
      </DockPanel>
    </DataTemplate>

    <DataTemplate x:Key="myCellTemplateMonth">
      <DockPanel>
        <TextBlock Foreground="DarkBlue" HorizontalAlignment="Center">
          <TextBlock.Text>
            <Binding Path="Month"/>
          </TextBlock.Text>
        </TextBlock>
      </DockPanel>
    </DataTemplate>
    <DataTemplate x:Key="myCellTemplateYear">
      <DockPanel>
        <TextBlock Foreground="DarkBlue" HorizontalAlignment="Center">
          <TextBlock.Text>
            <Binding Path="Year"/>
          </TextBlock.Text>
        </TextBlock>
      </DockPanel>
    </DataTemplate>
  </Window.Resources>
  <StackPanel>
      <ListView ItemsSource="{Binding Source={StaticResource myDateCollectionDataSource}}"
                HorizontalAlignment="Center">
        <ListView.View>
          <GridView>
            <GridViewColumn Header="Year" Width="80"
                  HeaderContainerStyle="{StaticResource myHeaderStyle}"
                  HeaderTemplate="{StaticResource myHeaderTemplate}"
                  CellTemplate="{StaticResource myCellTemplateYear}"/>
            <GridViewColumn Header="Month" Width="80"
                  HeaderContainerStyle="{StaticResource myHeaderStyle}"
                  HeaderTemplate="{StaticResource myHeaderTemplate}"
                  DisplayMemberBinding="{Binding Path=Month}"/>
            <GridViewColumn Header="Day" Width="80"
                  HeaderContainerStyle="{StaticResource myHeaderStyle}"
                  HeaderTemplate="{StaticResource myHeaderTemplate}"
                  CellTemplate="{StaticResource myCellTemplateDay}"/>
          </GridView>
        </ListView.View>
      </ListView>
  </StackPanel>

</Window>
//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Controls.Primitives;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {}

    public class myDateCollection :
            ObservableCollection<DateTime>
    {
        public myDateCollection()
        {
            Add(new DateTime(2005, 1, 1));
            Add(new DateTime(2004, 8, 1));
            Add(new DateTime(2003, 12, 4));
            Add(new DateTime(2004, 2, 18));
            Add(new DateTime(2004, 6, 30));
        }
    }
}

   
    
     


Use DataTemplate, DataTrigger, and DataTemplateSelector to specify the presentation of your data


   
  

<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:WpfApplication1"
  Title="Introduction to Data Templating Sample">
  <Window.Resources>
    <local:Employees x:Key="myTodoList"/>
    <local:EmployeeListDataTemplateSelector x:Key="myDataTemplateSelector"/>
    <DataTemplate x:Key="importantEmployeeTemplate">
      <DockPanel HorizontalAlignment="Center">
          <TextBlock Text="{Binding Path=Description}" />
      </DockPanel>
    </DataTemplate>
    <DataTemplate x:Key="myEmployeeTemplate">
    <StackPanel>
          <TextBlock Text="Employee Name:"/>
          <TextBlock Text="{Binding Path=EmployeeName}" />
          <TextBlock Text="Description:"/>
          <TextBlock Text="{Binding Path=Description}"/>
          <TextBlock Text="Priority:"/>
          <TextBlock Text="{Binding Path=Priority}"/>
    </StackPanel>
    <DataTemplate.Triggers>
      <DataTrigger Binding="{Binding Path=EmployeeType}">
        <DataTrigger.Value>
          <local:EmployeeType>Factory</local:EmployeeType>
        </DataTrigger.Value>
      </DataTrigger>
    </DataTemplate.Triggers>
    </DataTemplate>
  </Window.Resources>
  <StackPanel>
    <ListBox ItemsSource="{Binding Source={StaticResource myTodoList}}"
             ItemTemplateSelector="{StaticResource myDataTemplateSelector}"
             HorizontalContentAlignment="Stretch" 
             IsSynchronizedWithCurrentItem="True"/>
    <ContentControl Content="{Binding Source={StaticResource myTodoList}}"
                    ContentTemplate="{StaticResource myEmployeeTemplate}"/>
  </StackPanel>
</Window>


//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Data;
using System.Windows.Media;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace WpfApplication1
{    
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }

  public class Employee : INotifyPropertyChanged
  {
      private string name;
      private string description;
      private int priority;
      private EmployeeType type;


      public event PropertyChangedEventHandler PropertyChanged;

      public Employee()
      {
      }

      public Employee(string name, string description, int priority, EmployeeType type)
      {
          this.name = name;
          this.description = description;
          this.priority = priority;
          this.type = type;
      }

      public override string ToString()
      {
          return name.ToString();
      }

      public string EmployeeName
      {
          get { return name; }
          set
          {
              name = value;
              OnPropertyChanged("EmployeeName");
          }
      }

      public string Description
      {
          get { return description; }
          set
          {
              description = value;
              OnPropertyChanged("Description");
          }
      }

      public int Priority
      {
          get { return priority; }
          set
          {
              priority = value;
              OnPropertyChanged("Priority");
          }
      }

      public EmployeeType EmployeeType
      {
          get { return type; }
          set
          {
              type = value;
              OnPropertyChanged("EmployeeType");
          }
      }

      protected void OnPropertyChanged(string info)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(info));
          }
      }
  }
    public class Employees : ObservableCollection<Employee>
    {
        public Employees(): base()
        {
            Add(new Employee("A", "Cut", 2, EmployeeType.Factory));
            Add(new Employee("B", "Fix", 2, EmployeeType.Factory));
            Add(new Employee("C", "Email", 1, EmployeeType.Office));
            Add(new Employee("D", "Read", 3, EmployeeType.Office));
            Add(new Employee("E", "Clean", 1, EmployeeType.Factory));
            Add(new Employee("F", "Review", 2, EmployeeType.Office));
        }
    }

    public enum EmployeeType
    {
        Factory,
        Office
    }
    public class EmployeeListDataTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate
            SelectTemplate(object item, DependencyObject container)
        {
            if (item != null &amp;&amp; item is Employee)
            {
                Employee taskitem = item as Employee;
                Window window = Application.Current.MainWindow;

                if (taskitem.Priority == 1)
                    return
                        window.FindResource("importantEmployeeTemplate") as DataTemplate;
                else
                    return
                        window.FindResource("myEmployeeTemplate") as DataTemplate;
            }

            return null;
        }
    }
}

   
    
     


Use Data Templates to Display Bound Data

   
  

<Window 
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:WpfApplication1="clr-namespace:WpfApplication1"
    Title="WPF" Height="300" Width="300">

    <Window.Resources>
        <WpfApplication1:People x:Key="people"/>
        
        <DataTemplate x:Key="personTemplate">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="80"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>

                    <StackPanel>
                        <TextBlock
                            Style="{StaticResource lblStyle}"
                            Text="First Name" />
                        <TextBlock 
                            Style="{StaticResource dataStyle}"
                            Text="{Binding Path=FirstName}"/>
                        <TextBlock 
                            Style="{StaticResource lblStyle}"
                            Text="Age" />
                        <TextBlock 
                            Style="{StaticResource dataStyle}"
                            Text="{Binding Path=Age}" />
                    </StackPanel>

                    <Image 
                        Margin="4"
                        Grid.Column="1" 
                        Width="96"
                        Height="140"
                        Source="{Binding Path=Photo}"/>
                </Grid>
        </DataTemplate>


    </Window.Resources>

    <Grid>
        <ListBox
            ItemsSource="{Binding Source={StaticResource people}}"
            ItemTemplate="{StaticResource personTemplate}"/>


        <ListBox
            Margin="10"
            ItemsSource="{Binding Source={StaticResource people}}"/>
    </Grid>
</Window>
//File:Window.xaml.cs
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public class Employee
    {
        public string FirstName
        {
            get;
            set;
        }

        public int Age
        {
            get;
            set;
        }
        public string Photo
        {
            get;
            set;
        }

        public override string ToString()
        {
            return FirstName;
        }
    }

    public class People : Collection<Employee>
    {
        public People()
        {
            this.Add(new Employee()
                         {
                             FirstName = "A",
                             Age = 26,
                             Photo = "a.png"
                         });
            this.Add(new Employee()
                         {
                             FirstName = "C",
                             Age = 24,
                             Photo = "c.png"
                         });
        }
    }
}

   
    
     


DateTemplate for String


   
  

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:s="clr-namespace:System;assembly=mscorlib">
    <Page.Resources>

        <DataTemplate DataType="{x:Type s:String}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="String: " />
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>

    </Page.Resources>

    <StackPanel>
        <Button>
            <s:String>1</s:String>
        </Button>

    </StackPanel>
</Page>

   
    
     


DateTemplate for Date Time, filter value by path


   
  
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:s="clr-namespace:System;assembly=mscorlib">
    <Page.Resources>

        <DataTemplate DataType="{x:Type s:DateTime}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="DateTime: " />
                <TextBlock Text="{Binding Path=Month}" />
                <TextBlock Text="/" />
                <TextBlock Text="{Binding Path=Day}" />
                <TextBlock Text="/" />
                <TextBlock Text="{Binding Path=Year}" />
            </StackPanel>
        </DataTemplate>

    </Page.Resources>

    <StackPanel>
        <Button>
            <x:Static Member="s:DateTime.Now" />
        </Button>

    </StackPanel>
</Page>

   
    
     


DataTemplate for Int32


   
  
<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:s="clr-namespace:System;assembly=mscorlib">
    <Page.Resources>

        <DataTemplate DataType="{x:Type s:Int32}">
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Integer: " />
                <TextBlock Text="{Binding}" />
            </StackPanel>
        </DataTemplate>

    </Page.Resources>

    <StackPanel>
        <Button>
            <s:Int32>1</s:Int32>
        </Button>

    </StackPanel>
</Page>