Bind to an Existing Object Instance


   
  
<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


   
  
<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


   
 

<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







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








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







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

Create a Background Worker Thread in XAML








//File:Window.xaml.cs

using System;
using System.ComponentModel;
using System.Threading;
using System.Windows;
using System.Windows.Input;

namespace WpfApplication1
{
public partial class Window1 : Window
{
private readonly BackgroundWorker worker;

public Window1()
{
InitializeComponent();
worker = this.FindResource(“backgroundWorker”) as BackgroundWorker;
}

private void button_Click(object sender, RoutedEventArgs e)
{
if(!worker.IsBusy)
{
this.Cursor = Cursors.Wait;
worker.RunWorkerAsync();
button.Content = “Cancel”;
}else{
worker.CancelAsync();
}
}

private void BackgroundWorker_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
for(int i = 1; i <= 100; i++) { if(worker.CancellationPending) break; Thread.Sleep(100); worker.ReportProgress(i); } } private void BackgroundWorker_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e) { this.Cursor = Cursors.Arrow; Console.WriteLine(e.Error.Message); button.Content = "Start"; } private void BackgroundWorker_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e) { progressBar.Value = e.ProgressPercentage; } } } [/csharp]