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

    }
}

   
    
     


Implement INotifyPropertyChanged to notify the binding targets when the values of properties change.

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

    }
}

   
    
     


Bind to an Existing Object Instance

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" Height="140" Width="300">
    <Grid Margin="4">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="80"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>

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

        <TextBlock Margin="4" Text="First Name" VerticalAlignment="Center"/>
        <TextBox Margin="4" Text="{Binding Path=FirstName}"
                 Grid.Column="1"/>
        
        <TextBlock Margin="4" Text="Last Name" Grid.Row="1" VerticalAlignment="Center"/>
        <TextBox Margin="4" Text="{Binding Path=LastName}"
                 Grid.Column="1"
                 Grid.Row="1"/>
        
        <TextBlock Margin="4" Text="Age" Grid.Row="2" VerticalAlignment="Center"/>
        <TextBox Margin="4" Text="{Binding Path=Age}"
                 Grid.Column="1"
                 Grid.Row="2"/>
    </Grid>
</Window>
//File:Window.xaml.cs
using System.Windows;


namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            this.DataContext = new Employee()
                                   {
                                       FirstName = "A",
                                       LastName = "B",
                                       Age = 26
                                   };
        }
    }

    public class Employee
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
    }
}

   
    
     


Digital Clock

image_pdfimage_print


   
  
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
        xmlns:src="clr-namespace:MyNameSpace.DigitalClock"
        Title="Digital Clock"
        SizeToContent="WidthAndHeight">
    <Window.Resources>
        <src:ClockTicker1 x:Key="clock" />
    </Window.Resources>
    <Window.Content>
        <Binding Source="{StaticResource clock}" Path="DateTime" />
    </Window.Content>
</Window>
//File:Window.xaml.cs
using System;
using System.Windows;
using System.Windows.Threading;

namespace MyNameSpace.DigitalClock
{
    public class ClockTicker1 : DependencyObject
    {
        public static DependencyProperty DateTimeProperty = 
                DependencyProperty.Register("DateTime", typeof(DateTime), 
                                            typeof(ClockTicker1));
        
        public DateTime DateTime
        {
            set { SetValue(DateTimeProperty, value); }
            get { return (DateTime) GetValue(DateTimeProperty); }
        }

        public ClockTicker1()
        {
            DispatcherTimer timer = new DispatcherTimer();
            timer.Tick += TimerOnTick;
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Start();
        }

        void TimerOnTick(object sender, EventArgs args)
        {
            DateTime = DateTime.Now;
        }
    }
}