2012-05-19

Articles

DelegateCommand

 

The DelegateCommand is an implementation of the ICommand with the possibility to define which method will be called on execution of the ICommand. This is one of the most useful classes in MVVM environments. Such an object sometimes will be called RelayCommand.

 

alt

 

Usage

<UserControl x:Class="DW.SharpTools.Demo.DelegateCommandControl"
			 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
			 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
			 mc:Ignorable="d" 
			 d:DesignHeight="300" d:DesignWidth="300">
	<StackPanel HorizontalAlignment="Center">
		<Button Content="Lock / Unlock" Command="{Binding SwitchLockCommand}" />
		<Button Content="Edit" Command="{Binding EditCommand}" Margin="0,5,0,0" />
	</StackPanel>
</UserControl>
using System.Windows.Controls;
using System.Windows.Input;

namespace DW.SharpTools.Demo
{
	public partial class DelegateCommandControl : UserControl
	{
		public DelegateCommandControl()
		{
			InitializeComponent();
			DataContext = this;
			SwitchLockCommand = new DelegateCommand(p => SwitchLock());
			EditCommand = new DelegateCommand(p => CanEdit, p => Edit());
		}

		public ICommand SwitchLockCommand { get; set; }
		private void SwitchLock()
		{
			CanEdit = !CanEdit;
			((DelegateCommand)EditCommand).RaiseCanExecuteChanged();
		}

		public bool CanEdit { get; set; }

		public ICommand EditCommand { get; set; }
		private void Edit()
		{
		}
	}
}