Creating a KeyBinding between the Open command and Ctrl-R


   
  



<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="CommandHandlerProcedural"
    >
</Window>
//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            
            StackPanel MainStackPanel = new StackPanel();
            this.AddChild(MainStackPanel);

            Button CommandButton = new Button();
            CommandButton.Command = ApplicationCommands.Open;
            CommandButton.Content = "Open (KeyBindings: Ctrl-R, Ctrl-0)";
            MainStackPanel.Children.Add(CommandButton);

            CommandBinding OpenCmdBinding = new CommandBinding(ApplicationCommands.Open,OpenCmdExecuted,OpenCmdCanExecute);

            this.CommandBindings.Add(OpenCmdBinding);

            KeyBinding OpenCmdKeyBinding = new KeyBinding(ApplicationCommands.Open,Key.R,ModifierKeys.Control);

            this.InputBindings.Add(OpenCmdKeyBinding);
        }

        void OpenCmdExecuted(object target, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("The command has been invoked.");
        }

        void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
    }
}

   
    
     


Creating CommandBinding and attaching an Executed and CanExecute handler


   
  



<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="CommandHandlerProcedural"
    >
</Window>
//File:Window.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            
            StackPanel MainStackPanel = new StackPanel();
            this.AddChild(MainStackPanel);

            Button CommandButton = new Button();
            CommandButton.Command = ApplicationCommands.Open;
            CommandButton.Content = "Open (KeyBindings: Ctrl-R, Ctrl-0)";
            MainStackPanel.Children.Add(CommandButton);

            CommandBinding OpenCmdBinding = new CommandBinding(ApplicationCommands.Open,OpenCmdExecuted,OpenCmdCanExecute);

            this.CommandBindings.Add(OpenCmdBinding);

            KeyBinding OpenCmdKeyBinding = new KeyBinding(ApplicationCommands.Open,Key.R,ModifierKeys.Control);

            this.InputBindings.Add(OpenCmdKeyBinding);
        }

        void OpenCmdExecuted(object target, ExecutedRoutedEventArgs e)
        {
            MessageBox.Show("The command has been invoked.");
        }

        void OpenCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = true;
        }
    }
}

   
    
     


Button CommandTarget Binding


   
  


<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:custom="clr-namespace:WpfApplication1"
    Title="Custom RoutedCommand Sample"
    Name="RootWindow" Height="500" Width="600"
    Focusable="True">
  <Window.CommandBindings>
    <CommandBinding Command="{x:Static custom:Window1.ColorCmd}"
                    Executed="ColorCmdExecuted"
                    CanExecute="ColorCmdCanExecute"/>
  </Window.CommandBindings>
  <DockPanel>
    <Menu DockPanel.Dock="Top" Height="25">
      <MenuItem Header="Commands">
        <MenuItem Header="Color Command" Command="{x:Static custom:Window1.ColorCmd}" />
      </MenuItem>
    </Menu>
    <Border BorderBrush="Black" BorderThickness="1" Margin="10"
            Height="165" Width="250" DockPanel.Dock="Top">
      <TextBlock TextWrapping="Wrap" Margin="3">
        a
        <LineBreak/>
        b
        <LineBreak/>
        <LineBreak/>
        c
        <LineBreak/>
      </TextBlock>
    </Border>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" DockPanel.Dock="Bottom">
      <Border BorderBrush="Black" BorderThickness="1" Height="200" Width="200">
        <StackPanel Name="FirstStackPanel" Background="AliceBlue" Focusable="True">
          <StackPanel.CommandBindings>
            <CommandBinding Command="{x:Static custom:Window1.ColorCmd}" Executed="ColorCmdExecuted" CanExecute="ColorCmdCanExecute"/>
          </StackPanel.CommandBindings>

          <Label>StackPanel</Label>

          <Button Command="{x:Static custom:Window1.ColorCmd}"
                  CommandParameter="ButtonOne"
                  CommandTarget="{Binding ElementName=FirstStackPanel}" 
                  Content="CommandTarget = FristStackPanel" />
        </StackPanel>
      </Border>
      <Border BorderBrush="Black" BorderThickness="1" Height="200" Width="200">
        <StackPanel Background="AliceBlue" Focusable="True">
          <Label>Second StackPanel</Label>
        </StackPanel>
      </Border>
    </StackPanel>
  </DockPanel>
</Window>

//File:Window.xaml.cs


using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Input;


namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public static RoutedCommand ColorCmd = new RoutedCommand();
        public Window1()
        {
            InitializeComponent();
        }
        private void ColorCmdExecuted(object sender, ExecutedRoutedEventArgs e)
        {
            Panel target = e.Source as Panel;
            if (target != null)
            {
                if (target.Background == Brushes.AliceBlue)
                {
                    target.Background = Brushes.Red;
                }
                else
                {
                    target.Background = Brushes.AliceBlue;
                }
            }
        }
        private void ColorCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            if (e.Source is Panel)
            {
                e.CanExecute = true;
            }
            else
            {
                e.CanExecute = false;
            }
        }
    }
}

   
    
     


Help command


   
  

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        x:Class="AboutDialog"
        Title="About WPF Unleashed" SizeToContent="WidthAndHeight"
        Background="OrangeRed">
  <Window.CommandBindings>
    <CommandBinding Command="Help" CanExecute="HelpCanExecute" Executed="HelpExecuted"/>
  </Window.CommandBindings>
  <StackPanel>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">
      <Button MinWidth="75" Margin="10" Command="Help" Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
      <Button MinWidth="75" Margin="10">OK</Button>
    </StackPanel>
    <StatusBar>asdf</StatusBar>
  </StackPanel>
</Window>

//File:Window.xaml.cs

using System.Windows;
using System.Windows.Input;

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

    void HelpCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }
    
    void HelpExecuted(object sender, ExecutedRoutedEventArgs e)
    {
        System.Diagnostics.Process.Start("http://www.kutayzorlu.com/java2s/com");
    }
}

   
    
     


Built-In Command Bindings


   
       


<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <StackPanel xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                Orientation="Horizontal" Height="25">
      <Button Command="Cut" CommandTarget="{Binding ElementName=textBox}"
        Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
      <Button Command="Copy" CommandTarget="{Binding ElementName=textBox}"
        Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
      <Button Command="Paste" CommandTarget="{Binding ElementName=textBox}"
        Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
      <Button Command="Undo" CommandTarget="{Binding ElementName=textBox}"
        Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
      <Button Command="Redo" CommandTarget="{Binding ElementName=textBox}"
        Content="{Binding RelativeSource={RelativeSource Self}, Path=Command.Text}"/>
      <TextBox x:Name="textBox" Width="200"/>
    </StackPanel>
    

</Page>

   
    
    
    
    
    
    
     


Call the OnPropertyChanged method when its value changed


   
  

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

    }
}

   
    
     


View and Select Items Using a Combo Box


   
  
<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="100" Width="300">
    <StackPanel>
        <ComboBox Name="comboBox" IsEditable="True" Margin="5" SelectionChanged="ComboBox_SelectionChanged">
            <ComboBoxItem Content="ComboBox Item 1" Selected="ComboBoxItem_Selected" />
            <ComboBoxItem Content="ComboBox Item 2" Selected="ComboBoxItem_Selected" />
            <ComboBoxItem Content="ComboBox Item 3" Selected="ComboBoxItem_Selected" IsSelected="True"/>
            <ComboBoxItem Content="ComboBox Item 4" Selected="ComboBoxItem_Selected" />
            <ComboBoxItem Content="ComboBox Item 5" Selected="ComboBoxItem_Selected" />
        </ComboBox>
        <Button Content="Get Selected" Margin="5" Width="100" Click="Button_Click" />
    </StackPanel>
</Window>

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

namespace WpfApplication1
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ComboBoxItem item = comboBox.SelectedItem as ComboBoxItem;

            if (item != null)
            {
                MessageBox.Show("Current item: " + item.Content, Title);
            }
            else if (!String.IsNullOrEmpty(comboBox.Text))
            {
                MessageBox.Show("Text entered: " + comboBox.Text, Title);
            }
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

            if (!IsInitialized) return;

            ComboBoxItem item = comboBox.SelectedItem as ComboBoxItem;

            if (item != null)
            {
                MessageBox.Show("Selected item: " + item.Content, Title);
            }
        }

        private void ComboBoxItem_Selected(object sender,RoutedEventArgs e)
        {
            if (!IsInitialized) return;

            ComboBoxItem item = e.OriginalSource as ComboBoxItem;

            if (item != null)
            {
                MessageBox.Show(item.Content + " was selected.", Title);
            }
        }
    }
}