#1,083 – Setting CommandBindings in XAML
May 30, 2014 2 Comments
You can configure command bindings in code-behind, adding a CommandBinding object to a top-level window’s CommandBindings collection, as follows:
public MainWindow() { InitializeComponent(); this.DataContext = this; this.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, Executed_Open, CanExecute_Open)); }
You can set this command binding up in XAML, rather than in code-behind. Below is an example of doing the same binding in XAML.
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Commands" Width="320" Height="220"> <Window.CommandBindings> <CommandBinding Command="ApplicationCommands.Open" Executed="Executed_Open" CanExecute="CanExecute_Open"/> </Window.CommandBindings> <StackPanel> <Button Content="Open" Command="ApplicationCommands.Open" Margin="10" Padding="10,3" HorizontalAlignment="Center" /> <CheckBox Content="Can Open" IsChecked="{Binding CanOpenIsChecked}" Margin="10"/> </StackPanel> </Window>
This assumes that you’ve defined the following methods in code-behind:
public void Executed_Open(object sender, ExecutedRoutedEventArgs e) { MessageBox.Show("Executing the Open command"); } public void CanExecute_Open(object sender, CanExecuteRoutedEventArgs e) { e.CanExecute = CanOpenIsChecked; }
Pingback: Dew Drop – May 30, 2014 (#1787) | Morning Dew
Reblogged this on Dinesh Ram Kali..