Bind to a collection


   
  


<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="Binding to a Collection"
  SizeToContent="WidthAndHeight">
  <Window.Resources>
    <local:People x:Key="MyFriends"/>
    <DataTemplate x:Key="DetailTemplate">
       <StackPanel>
          <TextBlock Text="First Name:"/>
          <TextBlock Text="{Binding Path=FirstName}"/>
          <TextBlock Text="Last Name:"/>
          <TextBlock Text="{Binding Path=LastName}"/>
      </StackPanel>
    </DataTemplate>
  </Window.Resources>
  <StackPanel>
    <TextBlock>My Friends:</TextBlock>
    <ListBox Width="200" IsSynchronizedWithCurrentItem="True"
             ItemsSource="{Binding Source={StaticResource MyFriends}}"/>
    <TextBlock>Information:</TextBlock>
    <ContentControl Content="{Binding Source={StaticResource MyFriends}}"
                    ContentTemplate="{StaticResource DetailTemplate}"/>
  </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 Person : INotifyPropertyChanged
  {
      private string firstname;
      private string lastname;
      public event PropertyChangedEventHandler PropertyChanged;

      public Person()
      {
      }
      public Person(string first, string last)
      {
          this.firstname = first;
          this.lastname = last;
      }
      public override string ToString()
      {
          return firstname.ToString();
      }
      public string FirstName
      {
          get { return firstname; }
          set
          {
              firstname = value;
              OnPropertyChanged("FirstName");
          }
      }
      public string LastName
      {
          get { return lastname; }
          set
          {
              lastname = value;
              OnPropertyChanged("LastName");
          }
      }
      protected void OnPropertyChanged(string info)
      {
          PropertyChangedEventHandler handler = PropertyChanged;
          if (handler != null)
          {
              handler(this, new PropertyChangedEventArgs(info));
          }
      }
  }
    public class People : ObservableCollection<Person>
    {
        public People(): base()
        {
            Add(new Person("A", "Q"));
            Add(new Person("B", "E"));
            Add(new Person("C", "E"));
            Add(new Person("D", "R"));
        }
    }
}

   
    
     


Bind to IDataErrorInfo







//File:Window.xaml.cs
using System.Windows;
using System.ComponentModel;
namespace WpfApplication1
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
this.DataContext = new Employee(){FirstName = “A”,Age = 26,};
}
}

public class Employee : INotifyPropertyChanged,IDataErrorInfo
{
private string firstName;
private int age;

public Employee()
{
FirstName = “A”;
}
public string FirstName
{
get
{
return firstName;
}
set
{
if(firstName != value)
{
firstName = value;
OnPropertyChanged(“FirstName”);
}
}
}

public int Age
{
get
{
return age;
}
set
{
if(this.age != value)
{
this.age = value;
OnPropertyChanged(“Age”);
}
}
}

public event PropertyChangedEventHandler PropertyChanged;

private void OnPropertyChanged(string propertyName){
if(this.PropertyChanged != null)
{
this.PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
}
}
public string Error
{
get
{
return string.Empty;
}
}

public string this[string propertyName]
{
get
{
string message = string.Empty;

switch(propertyName)
{
case “FirstName”:
if(string.IsNullOrEmpty(firstName))
message = “A person must have a first name.”;
break;

case “Age”:
if(age < 1) message = "A person must have an age."; break; default: break; } return message; } } } } [/csharp]

Bind to a Collection with the Master-Detail Pattern


   
  

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="WPF" Height="370" Width="280">
    <Window.Resources>
        <DataTemplate 
            x:Key="masterTemplate">
            <TextBlock Margin="4" Text="{Binding Path=Description, UpdateSourceTrigger=PropertyChanged}"/>
        </DataTemplate>
        <DataTemplate x:Key="detailTemplate">
            <StackPanel>
               <TextBlock Text="First Name"/>
               <TextBox Text="{Binding Path=FirstName, Mode=TwoWay}"/>
               <TextBlock Text="Age"/>
               <TextBox Text="{Binding Path=Age, Mode=TwoWay}"/>
               <TextBlock Text="Occupation"/>
               <ComboBox x:Name="cboOccupation" IsEditable="False" Text="{Binding Path=Occupation, Mode=TwoWay}">
             <ComboBoxItem>Student</ComboBoxItem>
             <ComboBoxItem>Engineer</ComboBoxItem>
             <ComboBoxItem>Professional</ComboBoxItem>
        </ComboBox>
      </StackPanel>
        </DataTemplate>
    </Window.Resources>

    <StackPanel Margin="5">
        <ListBox ItemsSource="{Binding}" ItemTemplate="{StaticResource masterTemplate}" IsSynchronizedWithCurrentItem="True" />
        <ContentControl 
          Content="{Binding}"
          ContentTemplate="{StaticResource detailTemplate}" />
       
        <Button Click="AddButton_Click">Add Employee</Button>
    </StackPanel>
</Window>
//File:Window.xaml.cs

using System.Windows;
using System.ComponentModel;
using System;
using System.Collections.Generic;
using System.Text;
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 WpfApplication1
{
    public partial class Window1 : Window
    {
        EmployeeCollection people = new EmployeeCollection();

        public Window1()
        {
            InitializeComponent();
            this.DataContext = people;
        }

        private void AddButton_Click(object sender, RoutedEventArgs e)
        {
            people.Add(new Employee(){FirstName = "A",Age = 26});
        }
    }

    public class Employee : INotifyPropertyChanged
    {
        private string firstName;
        private int age;

        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                if(firstName != value)
                {
                    firstName = value;
                    OnPropertyChanged("FirstName");
                    OnPropertyChanged("Description");
                }
            }
        }
        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                if(this.age != value)
                {
                    this.age = value;
                    OnPropertyChanged("Age");
                    OnPropertyChanged("Description");
                }
            }
        }
        
        public string Description
        {
            get
            {
                return string.Format("{0})", firstName);
            }
        }
        public override string ToString()
        {
            return Description;
        }
        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if(this.PropertyChanged != null)
            {
                this.PropertyChanged(this,new PropertyChangedEventArgs(propertyName));
            }
        }
    }

    public class EmployeeCollection:ObservableCollection<Employee>
    {
        public EmployeeCollection()
        {
            Add(new Employee(){FirstName = "A",Age = 26,});

            Add(new Employee(){FirstName = "C",Age = 28,});

            Add(new Employee(){FirstName = "E",Age = 37,});

            Add(new Employee(){FirstName = "Q",Age = 25,});
        }
    }
}

   
    
     


Binding FontFamily / FontSize value for current Control


   
     

<StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            TextBlock.FontSize="12" >

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
        <TextBlock Text="This TextBlock has a FontFamily of " />
        <TextBlock Text="{Binding RelativeSource={RelativeSource self},Path=FontFamily}" />
        <TextBlock Text=" and a FontSize of " />
        <TextBlock Text="{Binding RelativeSource={RelativeSource self},Path=FontSize}" />
    </StackPanel>


</StackPanel>

   
    
    
    
    
     


Bind To TextBox Back and Forth


   
   

<Grid xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <Label Grid.Row="0" Grid.Column="0" 
           Margin="24 24 24 0"
           Content="Source TextBox Controls" />
    <Label Grid.Row="0" Grid.Column="1" 
           Margin="24 24 24 0"
           Content="Target TextBox Controls" />

    <TextBox Grid.Row="1" Grid.Column="0" Name="txtbox1" 
             Margin="24" />
    <TextBox Grid.Row="1" Grid.Column="1" 
             Margin="24" 
             Text="{Binding ElementName=txtbox1, Path=Text, Mode=TwoWay}" />

    <TextBox Grid.Row="2" Grid.Column="0" Name="txtbox2"  
             Margin="24" />
    <TextBox Grid.Row="2" Grid.Column="1" 
             Margin="24" 
             Text="{Binding ElementName=txtbox2, Path=Text, Mode=TwoWay}" />

    <TextBox Grid.Row="3" Grid.Column="0" Name="txtbox3"  
             Margin="24" />
    <TextBox Grid.Row="3" Grid.Column="1" 
             Margin="24" 
             Text="{Binding ElementName=txtbox3, Path=Text, Mode=TwoWay}" />

</Grid>

   
    
    
     


Bind TextBlock Text to SelectedItem property of ListBox


   
   

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

    <ListBox Name="lstbox"
             HorizontalAlignment="Center"
             Margin="24"
             ItemsSource="{Binding 
                            Source={x:Static g:DateTimeFormatInfo.CurrentInfo},
                            Path=DayNames,
                            Mode=OneTime}" />

    <TextBlock HorizontalAlignment="Center"
               Text="{Binding ElementName=lstbox, 
                                    Path=SelectedItem, Mode=OneWay}" />
</StackPanel>

   
    
    
     


Bind ListBox ItemsSource to DayNames property of DateTimeFormatInfo


   
   

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

    <ListBox Name="lstbox"
             HorizontalAlignment="Center"
             Margin="24"
             ItemsSource="{Binding 
                            Source={x:Static g:DateTimeFormatInfo.CurrentInfo},
                            Path=DayNames,
                            Mode=OneTime}" />
</StackPanel>