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

image_pdfimage_print


   
  

<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));
        }
    }
}

   
    
     


Data Trigger Sample

image_pdfimage_print


   
  

<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"));
        }
    }

}

   
    
     


Use DataTrigger and MultiDataTrigger.

image_pdfimage_print


   
  

<Window Background="Cornsilk"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:c="clr-namespace:WpfApplication1"
  x:Class="WpfApplication1.Window1"
  Title="DataTrigger Sample" Width = "320" Height = "300">
  <Window.Resources>
    <c:Employees x:Key="EmployeesData"/>
    <Style TargetType="ListBoxItem">
      <Style.Triggers>
        <DataTrigger Binding="{Binding Path=State}" Value="WA">
          <Setter Property="Foreground" Value="Red" />
        </DataTrigger>  
        <MultiDataTrigger>
          <MultiDataTrigger.Conditions>
            <Condition Binding="{Binding Path=Name}" Value="Portland" />
            <Condition Binding="{Binding Path=State}" Value="OR" />
          </MultiDataTrigger.Conditions>
          <Setter Property="Background" Value="Cyan" />
        </MultiDataTrigger>
      </Style.Triggers>
    </Style>

    <DataTemplate DataType="{x:Type c:Employee}">
      <Canvas Width="160" Height="20">
        <TextBlock Text="{Binding Path=Name}"/>
        <TextBlock Text="{Binding Path=State}"/>
      </Canvas>
    </DataTemplate>
  </Window.Resources>

  <StackPanel>
    <TextBlock FontSize="18" Margin="5" FontWeight="Bold"
      HorizontalAlignment="Center">Data Trigger Sample</TextBlock>
    <ListBox Width="180" HorizontalAlignment="Center" Background="Honeydew"
      ItemsSource="{Binding Source={StaticResource EmployeesData}}"/>
  </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.Navigation;
using System.Windows.Shapes;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
  public partial class Window1 : Window
  {
    public Window1()
    {
      InitializeComponent();
    }
  }
  public class Employee
  {
    private string _name;

    private string _state;

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

    public string State
    {
      get { return _state; }
      set { _state = value; }
    }

    public Employee(string name, string state)
    {
      this._name = name;
      this._state = state;
    }
  }

  public class Employees : ObservableCollection<Employee>
  {
    public Employees()
    {
      Add(new Employee("A", "WA"));
      Add(new Employee("B", "OR"));
      Add(new Employee("C", "WA"));
      Add(new Employee("D", "CA"));
    }
  }
}

   
    
     


Use Data Triggers to Change the Appearance of Bound Data

image_pdfimage_print


   
  
<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"
    x:Name="thisWindow" Title="WPF" Height="240" Width="280">

    <Window.Resources>
        <WpfApplication1:DataItems x:Key="dataItems"/>
        <WpfApplication1:AmountToHeightConverter x:Key="amountToHeightConverter" />
        <DataTemplate x:Key="dataItemtemplate">
            <Rectangle x:Name="rectangle" Width="30"
                VerticalAlignment="Bottom"
                Fill="Green"
                Height="{Binding Path=Amount,Converter={StaticResource amountToHeightConverter}}"/>
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding Path=IsPositive}" Value="False">
                    <Setter TargetName="rectangle" Property="Fill" Value="Red"/>
                </DataTrigger>
            </DataTemplate.Triggers>
        </DataTemplate>
    </Window.Resources>
    <StackPanel>
        <ItemsControl ItemsSource="{Binding Source={StaticResource dataItems}}"
            ItemTemplate="{StaticResource dataItemtemplate}">
            <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>

        <Line Stroke="Black" StrokeThickness="2" X1="0" Y1="0" X2="0" Y2="{Binding ElementName=thisWindow, Path=ActualHeight}"/>
        <Line Stroke="Black" StrokeThickness="2" X1="0" Y1="0" X2="{Binding ElementName=thisWindow, Path=ActualWidth}" Y2="0"/>
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System;
using System.Windows.Data;
using System.Globalization;
using System.Collections.ObjectModel;
namespace WpfApplication1
{
    [ValueConversion(typeof (double), typeof (double))]
    public class AmountToHeightConverter : IValueConverter
    {
        public Object Convert(Object value,Type targetType,Object parameter,CultureInfo culture)
        {
            double amount = System.Convert.ToDouble(value);
            if(amount < 0)
                amount = 0;

            return amount;
        }
        public object ConvertBack(object value,Type targetType,object parameter,CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    public class DataItem
    {
        public double Amount
        {
            get;
            set;
        }

        public bool IsPositive
        {
            get
            {
                return Amount >= 0;
            }
        }
    }

    public class DataItems : Collection<DataItem>
    {
        public DataItems()
        {
            this.Add(new DataItem(){Amount=5});
            this.Add(new DataItem(){Amount=8});
            this.Add(new DataItem(){Amount=-5});
            this.Add(new DataItem(){Amount=2});
            this.Add(new DataItem(){Amount=-5});
            this.Add(new DataItem(){Amount=-5});
        }
    }
}

   
    
     


DependencyProperty.RegisterReadOnly to create read only Dependency Property

image_pdfimage_print


   
  

<Window x:Name="winThis" x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="Create a Read-Only Dependency Property" Height="300" Width="300">
    <Grid>
      <Viewbox>
        <TextBlock Text="{Binding ElementName=winThis, Path=Counter}" />
      </Viewbox>
    </Grid>
</Window>

//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Threading;

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

            DispatcherTimer timer = 
                new DispatcherTimer(TimeSpan.FromSeconds(1), 
                                    DispatcherPriority.Normal, 
                                    delegate 
                                    {
                                        int newValue = Counter == int.MaxValue ? 0 : Counter + 1;
                                        SetValue(counterKey, newValue); 
                                    }, 
                                    Dispatcher);
        }

        public int Counter
        {
            get { return (int)GetValue(counterKey.DependencyProperty); }
        }

        private static readonly DependencyPropertyKey counterKey = 
            DependencyProperty.RegisterReadOnly("Counter", 
                                                typeof(int), 
                                                typeof(Window1), 
                                                new PropertyMetadata(0));
    }
}

   
    
     


Clear locally set values and restore the default values of dependency properties

image_pdfimage_print


   
  
<StackPanel Name="root"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  x:Class="WpfApplication1.DPClearValue">
    <StackPanel.Resources>
      <Style TargetType="Button">
        <Setter Property="Height" Value="20"/>
        <Setter Property="Width" Value="250"/>
        <Setter Property="HorizontalAlignment" Value="Left"/>
      </Style>
      <Style TargetType="Ellipse">
        <Setter Property="Height" Value="50"/>
        <Setter Property="Width" Value="50"/>
        <Setter Property="Fill" Value="Black"/>
      </Style>
      <Style TargetType="Rectangle">
        <Setter Property="Height" Value="50"/>
        <Setter Property="Width" Value="50"/>
        <Setter Property="Fill" Value="Blue"/>
      </Style>
      <Style TargetType="Polygon">
        <Setter Property="Points" Value="10,60 60,60 60,10"/>
        <Setter Property="Fill" Value="Blue"/>
      </Style>
      <Style x:Key="ShapeStyle" TargetType="Shape">
        <Setter Property="Fill" Value="Red"/>
      </Style>
    </StackPanel.Resources>
  <DockPanel Name="myDockPanel">
    <Ellipse Height="100"  Width="100" Style="{StaticResource ShapeStyle}"/>
    <Rectangle Height="100" Width="100"  Style="{StaticResource ShapeStyle}" />
    <Polygon Points="10,110 110,110 110,10" Style="{StaticResource ShapeStyle}"/>
  </DockPanel>
    <Button Name="RedButton" Click="MakeEverythingRed">Make everything red</Button>
    <Button Name="ClearButton" Click="RestoreDefaultProperties">
  Clear local values
  </Button>

</StackPanel>

//File:Window.xaml.cs


using System.Windows;
using System.Collections;
using System.Windows.Media;
using System.Windows.Controls;
using System.Windows.Shapes;

namespace WpfApplication1 {
    public partial class DPClearValue {
        void RestoreDefaultProperties(object sender, RoutedEventArgs e)
        {
            UIElementCollection uic = myDockPanel.Children;
            foreach (Shape uie in uic)
            {
                LocalValueEnumerator locallySetProperties = uie.GetLocalValueEnumerator();
                while (locallySetProperties.MoveNext())
                {
                    DependencyProperty propertyToClear = (DependencyProperty)locallySetProperties.Current.Property;
                    if (!propertyToClear.ReadOnly) { uie.ClearValue(propertyToClear); }
                }
            }
        }
        void MakeEverythingRed(object sender, RoutedEventArgs e)
        {
            UIElementCollection uic = myDockPanel.Children;
            foreach (Shape uie in uic) {uie.Fill = new SolidColorBrush(Colors.Red);}
        }
    }
}

   
    
     


Add a PropertyChangedValueCallback to Any Dependency Property

image_pdfimage_print


   
  
<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title=" " Height="300" Width="300" Loaded="Window1_Loaded">
  <Grid>
    <Viewbox>
      <TextBox x:Name="tbxEditMe" Text="Edit Me..." />
    </Viewbox>      
  </Grid>
</Window>


//File:Window.xaml.cs
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;

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

        private void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            DependencyPropertyDescriptor descriptor = DependencyPropertyDescriptor.FromProperty(TextBox.TextProperty, typeof(TextBox));
            descriptor.AddValueChanged(tbxEditMe, tbxEditMe_TextChanged);
            
        }

        private void tbxEditMe_TextChanged(object sender, EventArgs e)
        {
            MessageBox.Show("", "changed");
        }
    }
}