Bind to the Values of an Enumeration


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

    <Window.Resources>
        <ObjectDataProvider x:Key="daysData" MethodName="GetValues" ObjectType="{x:Type System:Enum}" >
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="WpfApplication1:DaysOfTheWeek"/>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

    </Window.Resources>
    
    <StackPanel>
        <TextBlock Margin="5" Text="Select the day of the week:"/>
        <ComboBox Margin="5" ItemsSource="{Binding Source={StaticResource daysData}}" />
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;

namespace WpfApplication1
{
    public enum DaysOfTheWeek
    {
        Monday,
        Tuesday,
        Wednesday,
        Thursday,
        Friday,
        Saturday,
        Sunday
    }

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

   
    
     


Bind an ItemsControl to the CollectionViewSource, Set its DisplayMemberPath to display the Name property


   
  

<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="WPF" Height="124" Width="124">
    <Window.Resources>
        <local:Countries x:Key="countries"/>
        <CollectionViewSource x:Key="cvs" Source="{Binding Source={StaticResource countries}}"
            Filter="CollectionViewSource_EuropeFilter" />
    </Window.Resources>
    <Grid>

        <ItemsControl ItemsSource="{Binding Source={StaticResource cvs}}"
            DisplayMemberPath="Name"/>
    </Grid>

</Window>
//File:Window.xaml.cs
using System.Windows;
using System.Windows.Data;
using System.Collections.ObjectModel;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        private void CollectionViewSource_EuropeFilter(object sender, FilterEventArgs e)
        {
            Country country = e.Item as Country;
            e.Accepted = (country.Continent == Continent.Europe);
        }
    }

    public class Country
    {
        private string name;
        private Continent continent;

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

        public Continent Continent
        {
            get{return continent;}
            set{continent = value;}
        }

        public Country(string name, Continent continent)
        {
            this.name = name;
            this.continent = continent;
        }
    }

    public enum Continent
    {
        Europe,
        NorthAmerica,
    }

    public class Countries : Collection<Country>
    {
        public Countries()
        {
            this.Add(new Country("Great Britan", Continent.Europe));
            this.Add(new Country("USA", Continent.NorthAmerica));
            this.Add(new Country("Canada", Continent.NorthAmerica));
        }
    }
}

   
    
     


Bind to a Method


   
  
<Window 
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:system="clr-namespace:System;assembly=mscorlib"
  xmlns:WpfApplication1="clr-namespace:WpfApplication1"
    Title="WPF"  Width="240" Height="150" >
    <Window.Resources>
        <WpfApplication1:DoubleToString x:Key="doubleToString" />
        <ObjectDataProvider x:Key="convertDistance"
            ObjectType="{x:Type WpfApplication1:DistanceConverter }"
            MethodName="Convert" >
            <ObjectDataProvider.MethodParameters>
                <system:Double>0</system:Double>
                <WpfApplication1:DistanceType>Miles</WpfApplication1:DistanceType>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

    </Window.Resources>
    <StackPanel>
        <TextBlock Text="Enter a distance to convert:"/>
        <TextBox Text ="{Binding Source={StaticResource convertDistance},
                    Path=MethodParameters&#91;0&#93;,BindsDirectlyToSource=true,UpdateSourceTrigger=PropertyChanged,
                    Converter={StaticResource doubleToString}}"/>
        
        <ComboBox Width="80" HorizontalAlignment="Left"
            SelectedValue="{Binding Source={StaticResource convertDistance},Path=MethodParameters&#91;1&#93;, 
                            BindsDirectlyToSource=true}" >
            <WpfApplication1:DistanceType>Miles</WpfApplication1:DistanceType>
            <WpfApplication1:DistanceType>Kilometres</WpfApplication1:DistanceType>
        </ComboBox>

        <TextBlock Text="Result:"/>
        <TextBlock Text="{Binding Source={StaticResource convertDistance}}"/>
    </StackPanel>
</Window>


//File:Window.xaml.cs

using System;
using System.Windows.Data;

namespace WpfApplication1
{
    public class DoubleToString : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
        {
            if(value != null)
            {
                return value.ToString();
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
        {
            string strValue = value as string;
            if(strValue != null)
            {
                double result;
                bool converted = Double.TryParse(strValue, out result);
                if(converted)
                {
                    return result;
                }
            }
            return null;
        }
    }


    public enum DistanceType
    {
        Miles,
        Kilometres
    }

    public class DistanceConverter
    {
        public string Convert(double amount, DistanceType distancetype)
        {
            if(distancetype == DistanceType.Miles)
                return (amount * 1.6).ToString("0.##") + " km";

            if(distancetype == DistanceType.Kilometres)
                return (amount * 0.6).ToString("0.##") + " m";

            throw new ArgumentOutOfRangeException("distanceType");
        }
    }
}

   
    
     


Bind to enum types


   
  
<Window 
    x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:system="clr-namespace:System;assembly=mscorlib"
  xmlns:WpfApplication1="clr-namespace:WpfApplication1"
    Title="WPF"  Width="240" Height="150" >
    <Window.Resources>
        <WpfApplication1:DoubleToString x:Key="doubleToString" />
        <ObjectDataProvider x:Key="convertDistance"
            ObjectType="{x:Type WpfApplication1:DistanceConverter }"
            MethodName="Convert" >
            <ObjectDataProvider.MethodParameters>
                <system:Double>0</system:Double>
                <WpfApplication1:DistanceType>Miles</WpfApplication1:DistanceType>
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>

    </Window.Resources>
    <StackPanel>
        <TextBlock Text="Enter a distance to convert:"/>
        <TextBox Text ="{Binding Source={StaticResource convertDistance},
                    Path=MethodParameters&#91;0&#93;,BindsDirectlyToSource=true,UpdateSourceTrigger=PropertyChanged,
                    Converter={StaticResource doubleToString}}"/>
        
        <ComboBox Width="80" HorizontalAlignment="Left"
            SelectedValue="{Binding Source={StaticResource convertDistance},Path=MethodParameters&#91;1&#93;, 
                            BindsDirectlyToSource=true}" >
            <WpfApplication1:DistanceType>Miles</WpfApplication1:DistanceType>
            <WpfApplication1:DistanceType>Kilometres</WpfApplication1:DistanceType>
        </ComboBox>

        <TextBlock Text="Result:"/>
        <TextBlock Text="{Binding Source={StaticResource convertDistance}}"/>
    </StackPanel>
</Window>


//File:Window.xaml.cs

using System;
using System.Windows.Data;

namespace WpfApplication1
{
    public class DoubleToString : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
        {
            if(value != null)
            {
                return value.ToString();
            }
            return null;
        }

        public object ConvertBack(object value, Type targetType, object parameter,System.Globalization.CultureInfo culture)
        {
            string strValue = value as string;
            if(strValue != null)
            {
                double result;
                bool converted = Double.TryParse(strValue, out result);
                if(converted)
                {
                    return result;
                }
            }
            return null;
        }
    }


    public enum DistanceType
    {
        Miles,
        Kilometres
    }

    public class DistanceConverter
    {
        public string Convert(double amount, DistanceType distancetype)
        {
            if(distancetype == DistanceType.Miles)
                return (amount * 1.6).ToString("0.##") + " km";

            if(distancetype == DistanceType.Kilometres)
                return (amount * 0.6).ToString("0.##") + " m";

            throw new ArgumentOutOfRangeException("distanceType");
        }
    }
}

   
    
     


Collection View Source Binding























//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.ComponentModel;
using System.Collections.ObjectModel;

namespace WpfApplication1 {

public class Employee : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propName) {
if( this.PropertyChanged != null ) {
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}

string name;
public string Name {
get { return this.name; }
set {
if( this.name == value ) { return; }
this.name = value;
Notify(“Name”);
}
}

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

public Employee() { }
public Employee(string name, int age) {
this.name = name;
this.age = age;
}
}

class People : ObservableCollection { }

public partial class Window1 : System.Windows.Window {
public Window1() {
InitializeComponent();
}

}

public class AgeToRangeConverter : IValueConverter {

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
return (int)value < 25 ? "Under 25" : "Over 25"; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } } [/csharp]

BindingOperations.GetBindingExpression


   
  



<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="ManualUpdateTarget" Height="135" Width="200">
  <Window.Resources>
    <local:Person x:Key="Tom" Name="Tom" Age="11" />
  </Window.Resources>
  <StackPanel DataContext="{StaticResource Tom}">
    <TextBlock Margin="5" VerticalAlignment="Center">Name:</TextBlock>
    <TextBox Margin="5" Name="nameTextBox" Text="{Binding Path=Name}" />
    <TextBlock Margin="5" VerticalAlignment="Center">Age:</TextBlock>
    <TextBox Margin="5" Name="ageTextBox" Text="{Binding Path=Age}" />
    <Button Margin="5" Width="75" Name="birthdayButton">Birthday</Button>
  </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.ComponentModel;

namespace WpfApplication1 {
  public class Person {
    string name;
    public string Name {
      get { return this.name; }
      set {
        if( this.name == value ) { return; }
        this.name = value;
      }
    }

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

    public Person() { }
    public Person(string name, int age) {
      this.name = name;
      this.age = age;
    }
  }

  public partial class Window1 : System.Windows.Window {
    public Window1() {
      InitializeComponent();
      this.birthdayButton.Click += birthdayButton_Click;
    }

    void birthdayButton_Click(object sender, RoutedEventArgs e) {
      Person person = (Person)this.FindResource("Tom");
      person.Age = person.Age+1;
      BindingOperations.GetBindingExpression(ageTextBox, TextBox.TextProperty).UpdateTarget();

      Console.WriteLine(person.Name);
      Console.WriteLine(person.Age);
    }
  }
}

   
    
     


Hierarchical Binding for three level nested objects


   
  
<Window x:Class="WpfApplication1.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Title="HierarchicalBinding" xmlns:local="clr-namespace:WpfApplication1">
  <Window.Resources>
    <local:Companies x:Key="Companies">
      <local:Company CompanyName="CompanyA">
        <local:Company.Members>
          <local:People>
            <local:Employee Name="EmployeeA" Age="21">
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment1" />
                  <local:Comment Description="Comment2" />
                  <local:Comment Description="Comment3" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
            <local:Employee Name="Moe" Age="22" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Nice" />
                  <local:Comment Description="Comment3" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
            <local:Employee Name="Curly" Age="23" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment6" />
                  <local:Comment Description="Comment3" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
          </local:People>
        </local:Company.Members>
      </local:Company>
      <local:Company CompanyName="CompanyB">
        <local:Company.Members>
          <local:People>
            <local:Employee Name="EmployeeB" Age="135" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment8" />
                  <local:Comment Description="Comment7" />
                  <local:Comment Description="Comment5" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
            <local:Employee Name="EmployeeC" Age="121" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment8" />
                  <local:Comment Description="Pale" />
                  <local:Comment Description="Comment4" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
            <local:Employee Name="EmployeeD" Age="137" >
              <local:Employee.Comments>
                <local:Comments>
                  <local:Comment Description="Comment8" />
                  <local:Comment Description="Comment6" />
                  <local:Comment Description="Comment3" />
                </local:Comments>
              </local:Employee.Comments>
            </local:Employee>
          </local:People>
        </local:Company.Members>
      </local:Company>
    </local:Companies>

    <HierarchicalDataTemplate DataType="{x:Type local:Company}"
      ItemsSource="{Binding Path=Members}">
      <TextBlock Text="{Binding Path=CompanyName}" />
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="{x:Type local:Employee}"
      ItemsSource="{Binding Path=Comments}">
      <TextBlock>
        <TextBlock Text="{Binding Path=Name}" />
        (age: <TextBlock Text="{Binding Path=Age}" />)
      </TextBlock>
    </HierarchicalDataTemplate>

    <DataTemplate DataType="{x:Type local:Comment}">
      <TextBlock Text="{Binding Path=Description}" />
    </DataTemplate>

  </Window.Resources>

  <TreeView DataContext="{StaticResource Companies}">
    <TreeViewItem ItemsSource="{Binding}" Header="Companies" />
  </TreeView>
</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.Collections.ObjectModel;


namespace WpfApplication1 {

  public class Comment {
    string description;
    public string Description {
      get { return description; }
      set { description = value; }
    }
  }

  public class Comments : ObservableCollection<Comment> { }

  public class Employee {
    string name;
    public string Name {
      get { return name; }
      set { name = value; }
    }

    int age;
    public int Age {
      get { return age; }
      set { age = value; }
    }

    Comments traits;
    public Comments Comments {
      get { return traits; }
      set { traits = value; }
    }
  }

  public class People : ObservableCollection<Employee> { }

  public class Company {
    string familyName;
    public string CompanyName {
      get { return familyName; }
      set { familyName = value; }
    }

    People members;
    public People Members {
      get { return members; }
      set { members = value; }
    }
  }

  public class Companies : ObservableCollection<Company> { }

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