2012-05-19

Articles

DeleteBehavior

 

Need a command if the user wants to "delete" an item out of a list? Take this behavior. Simply attach it to any kind of control and it listen to the key inputs, as soon the user have pressed the delete key a corresponding command will be called.

 

alt

 

Usage

<UserControl x:Class="DW.Interactivity.Demo.DeleteBehaviorControl"
			 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
			 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
			 xmlns:Interactivity="http://schemas.my-libraries.de/wpf/interactivity">
	<DockPanel Height="300">
		<Button Content="Add Item" DockPanel.Dock="Bottom" Click="Button_Click" />
		<ListBox ItemsSource="{Binding Items}">
			<ListBox.ItemContainerStyle>
				<Style TargetType="{x:Type ListBoxItem}">
					<Setter Property="Interactivity:DeleteBehavior.Command"
							Value="{Binding DataContext.DeleteItemCommand, RelativeSource={
										RelativeSource FindAncestor, AncestorType={
											x:Type UserControl
										}
									}}" />
				</Style>
			</ListBox.ItemContainerStyle>
		</ListBox>
	</DockPanel>
</UserControl>
using System;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using DW.SharpTools;

namespace DW.Interactivity.Demo
{
	public partial class DeleteBehaviorControl : UserControl
	{
		public DeleteBehaviorControl()
		{
			InitializeComponent();
			DataContext = this;

			Items = new ObservableCollection<string>();

			DeleteItemCommand = new DelegateCommand(p => DeleteItem(p));
		}

		public ObservableCollection<string> Items { get; set; }

		public ICommand DeleteItemCommand { get; set; }
		private void DeleteItem(object item)
		{
			Items.Remove((string)item);
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			Items.Add(Guid.NewGuid().ToString());
		}
	}
}