Collection View Source Binding

image_pdfimage_print























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

Bind to enum types

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: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 a Method

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: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 an ItemsControl to the CollectionViewSource, Set its DisplayMemberPath to display the Name 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"
    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 the Values of an Enumeration

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

   
    
     


Binding Dependency Property to TextBlock

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

   
    
     


Bind Your Objects to UI Control with 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="WPF WpfApplication1" Height="180" Width="260">
    <StackPanel>
        <TextBlock Text="Last Name" VerticalAlignment="Center"/>
        <TextBox Text="{Binding Path=LastName, Mode=TwoWay}"/>
        
        <TextBlock Text="Age" VerticalAlignment="Center"/>
        <TextBox Text="{Binding Path=Age, Mode=TwoWay}"/>
        
        <TextBlock Text="Occupation" VerticalAlignment="Center"/>
        <ComboBox x:Name="cboOccupation" IsEditable="False" HorizontalAlignment="Left"
            Text="{Binding Path=Occupation, Mode=TwoWay}"
            Margin="4" Width="140">
             <ComboBoxItem>Student</ComboBoxItem>
             <ComboBoxItem>Skilled</ComboBoxItem>
             <ComboBoxItem>Professional</ComboBoxItem>
        </ComboBox>
                  
        <TextBlock Margin="4" Text="Description" FontWeight="Bold" FontStyle="Italic" VerticalAlignment="Center"/>
        <TextBlock Margin="4" Text="{Binding Path=Description, UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center"/>
        
    </StackPanel>
</Window>
//File:Window.xaml.cs
using System.Windows;
using System.ComponentModel;
namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            
            this.DataContext = new Employee(){
                        LastName = "B",
                        Age = 26,
                        Occupation = "Professional"
            };
        }
    }

    public class Employee : INotifyPropertyChanged
    {
        private string lastName;
        private int age;
        private string occupation;

        public string LastName
        {
            get
            {
                return lastName;
            }
            set
            {
                if(this.lastName != value)
                {
                    this.lastName = value;
                    OnPropertyChanged("LastName");
                    OnPropertyChanged("Description");
                }
            }
        }

        public int Age
        {
            get
            {
                return age;
            }
            set
            {
                if(this.age != value)
                {
                    this.age = value;
                    OnPropertyChanged("Age");
                    OnPropertyChanged("Description");
                }
            }
        }
        
        public string Occupation
        {
            get { return occupation; }
            set
            {
                if (this.occupation != value)
                {
                    this.occupation = value;
                    OnPropertyChanged("Occupation");
                    OnPropertyChanged("Description");
                }
            }
        }

        public string Description
        {
            get
            {
                return string.Format("{0} {1}, ({2})", 
                                     lastName, age, occupation);
            }
        }


        public event PropertyChangedEventHandler PropertyChanged;

        private void OnPropertyChanged(string propertyName)
        {
            if(this.PropertyChanged != null)
            {

                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

    }
}