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

   
    
     


Add ApplicationCommands.Cut to TextBox with TextBox.CommandBindings

image_pdfimage_print


   
 

<Window x:Class="Commands.NoCommandTextBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NoCommandTextBox" Height="300" Width="300">
    <Grid>
      <TextBox Name="txt"/>
    </Grid>
</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;

namespace Commands
{
    public partial class NoCommandTextBox : System.Windows.Window
    {
        public NoCommandTextBox()
        {
            InitializeComponent();           
        
            txt.CommandBindings.Add(new CommandBinding(ApplicationCommands.Cut, null, SuppressCommand));

        }
     
        private void SuppressCommand(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = false;
            e.Handled = true;
        }
    }
}

   
     


Execute a Method Asynchronously Using a Background Worker Thread

image_pdfimage_print







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

namespace WpfApplication1
{
public partial class Window1 : Window
{
private BackgroundWorker worker = new BackgroundWorker();

private long from= 1;
private long to = 200;
private long biggestPrime;

public Window1(): base()
{
InitializeComponent();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}

private void Start_Click(object sender, RoutedEventArgs e)
{
worker.RunWorkerAsync();
btnStart.IsEnabled = false;
txtBiggestPrime.Text = string.Empty;
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnStart.IsEnabled = true;
txtBiggestPrime.Text = biggestPrime.ToString();
}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
for(long current = from; current <= to; current++) { biggestPrime = current; } } } } [/csharp]

Track the Progress of a Background Worker Thread

image_pdfimage_print








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

namespace WpfApplication1
{
public partial class Window1 : Window
{
private BackgroundWorker worker = new BackgroundWorker();

private long from = 2;
private long to = 20000;
private long biggestPrime;

public Window1() : base()
{
InitializeComponent();
worker.WorkerReportsProgress = true;

worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
worker.ProgressChanged += worker_ProgressChanged;
}

private void StartStop_Click(object sender, RoutedEventArgs e)
{
worker.RunWorkerAsync();
btnStartStop.IsEnabled = false;
txtBiggestPrime.Text = string.Empty;
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnStartStop.IsEnabled = true;
txtBiggestPrime.Text = biggestPrime.ToString();
}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
for(long current = from; current <= to; current++){ biggestPrime = current; int percentComplete = Convert.ToInt32(((double) current / to) * 100d); worker.ReportProgress(percentComplete); System.Threading.Thread.Sleep(10); } } private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e) { txtPercent.Text = e.ProgressPercentage.ToString() + "%"; } } } [/csharp]

Support the Cancellation of a Background Worker Thread

image_pdfimage_print







//File:Window.xaml.cs

using System;
using System.ComponentModel;
using System.Windows;

namespace WpfApplication1
{
public partial class Window1 : Window
{
private BackgroundWorker worker = new BackgroundWorker();

private long from = 2;
private long to = 2000;
private long biggestPrime;

public Window1(): base()
{
InitializeComponent();
worker.WorkerSupportsCancellation = true;
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}
private void StartStop_Click(object sender, RoutedEventArgs e)
{
if(!worker.IsBusy)
{
worker.RunWorkerAsync();
btnStartStop.Content = “Cancel”;
txtBiggestPrime.Text = string.Empty;
}
else
{
worker.CancelAsync();
}
}

private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if(e.Cancelled)
{
MessageBox.Show(“Operation was canceled”);
}

btnStartStop.Content = “Start”;
txtBiggestPrime.Text = biggestPrime.ToString();
}

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
for(long current = from; current <= to; current++) { if(worker.CancellationPending) { e.Cancel = true; return; } biggestPrime = current; } } } } [/csharp]