一、公共类
namespace Gh.Ticket.Common
{
public class ExtendedCommandParameter
{
public ExtendedCommandParameter(EventArgs eventArgs, FrameworkElement sender, object parameter)
{
EventArgs = eventArgs;
Sender = sender;
Parameter = parameter;
}
public EventArgs EventArgs { get; private set; }
public FrameworkElement Sender { get; private set; }
public object Parameter { get; private set; }
}
public class ExtendedInvokeCommandAction : TriggerAction<FrameworkElement>
{
public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(ExtendedInvokeCommandAction), new PropertyMetadata(null, CommandChangedCallback));
public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.Register("CommandParameter", typeof(object), typeof(ExtendedInvokeCommandAction), new PropertyMetadata(null, CommandParameterChangedCallback));
private static void CommandParameterChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var invokeCommand = d as ExtendedInvokeCommandAction;
if (invokeCommand != null)
invokeCommand.SetValue(CommandParameterProperty, e.NewValue);
}
private static void CommandChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var invokeCommand = d as ExtendedInvokeCommandAction;
if (invokeCommand != null)
invokeCommand.SetValue(CommandProperty, e.NewValue);
}
protected override void Invoke(object parameter)
{
if (this.Command == null)
return;
if (this.Command.CanExecute(parameter))
{
var commandParameter = new ExtendedCommandParameter(parameter as EventArgs, this.AssociatedObject,
GetValue(CommandParameterProperty));
this.Command.Execute(commandParameter);
}
}
#region public properties
public object CommandParameter
{
get { return GetValue(CommandParameterProperty); }
set { SetValue(CommandParameterProperty, value); }
}
public ICommand Command
{
get { return GetValue(CommandProperty) as ICommand; }
set { SetValue(CommandParameterProperty, value); }
}
#endregion
}
}
二、View层
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="ExtendedInvokeCommandAction类所在命名空间"
<TextBox x:Name="txtControlID" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="PreviewKeyDown">
<local:ExtendedInvokeCommandAction
Command="{Binding CustomCommand}"
CommandParameter="{Binding}"
/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
三、ViewMode层
public ICommand CustomCommand
{
get
{
return new DelegateCommand<object>(x =>
{
ExtendedCommandParameter p = x as ExtendedCommandParameter;
p.sender 触发事件对象
p.EventArgs 事件参数
});
}
}