using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
namespace MouseCommandBehavior
{
public static class MouseDownUpCommandBehavior
{
///
/// The comamnd which should be executed when the mouse is down
///
public static readonly DependencyProperty MouseDownCommandProperty =
DependencyProperty.RegisterAttached("MouseDownCommand",
typeof(ICommand),
typeof(MouseDownUpCommandBehavior),
new FrameworkPropertyMetadata(null, (obj, e) =>
OnMouseCommandChanged(obj, (ICommand)e.NewValue, "MouseDown")));
///
/// The comamnd which should be executed when the mouse is up
///
public static readonly DependencyProperty MouseUpCommandProperty =
DependencyProperty.RegisterAttached("MouseUpCommand",
typeof(ICommand),
typeof(MouseDownUpCommandBehavior),
new FrameworkPropertyMetadata(null, (obj, e) =>
OnMouseCommandChanged(obj, (ICommand)e.NewValue, "MouseUp")));
public static readonly DependencyProperty CommandParameterProperty =
DependencyProperty.RegisterAttached(
"CommandParameter",
typeof(object),
typeof(MouseDownUpCommandBehavior),
new PropertyMetadata(OnSetParameter));
public static void SetCommandParameter(Control control, object parameter)
{
control.SetValue(CommandParameterProperty, parameter);
}
public static object GetCommandParameter(Control buttonBase)
{
return buttonBase.GetValue(CommandParameterProperty);
}
private static void OnSetParameter(DependencyObject d,
DependencyPropertyChangedEventArgs args)
{
d.SetValue(CommandParameterProperty, args.NewValue);
}
///
/// Gets the MouseDownCommand property
///
public static ICommand GetMouseDownCommand(DependencyObject d)
{
return (ICommand)d.GetValue(MouseDownCommandProperty);
}
///
/// Sets the MouseDownCommand property
///
public static void SetMouseDownCommand(DependencyObject d, ICommand value)
{
d.SetValue(MouseDownCommandProperty, value);
}
///
/// Gets the MouseUpCommand property
///
public static ICommand GetMouseUpCommand(DependencyObject d)
{
return (ICommand)d.GetValue(MouseUpCommandProperty);
}
///
/// Sets the MouseUpCommand property
///
public static void SetMouseUpCommand(DependencyObject d, ICommand value)
{
d.SetValue(MouseUpCommandProperty, value);
}
///
/// Registers the event and calls the command when it gets fired
///
private static void OnMouseCommandChanged(DependencyObject d,
ICommand command, string routedEventName)
{
if (String.IsNullOrEmpty(routedEventName) || command == null) return;
var element = (FrameworkElement)d;
switch (routedEventName)
{
case "MouseDown":
element.PreviewMouseDown += (obj, e) =>
command.Execute(d.GetValue(CommandParameterProperty));
break;
case "MouseUp":
element.PreviewMouseUp += (obj, e) =>
command.Execute(d.GetValue(CommandParameterProperty));
break;
}
}
}
}
MouseCommand.zip