Ответ 1
Нет встроенного способа, так вот как я это делаю:
Классический триггер взаимодействия используется следующим образом:
<Button Content="I am a button">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<i:InvokeCommandAction Command="{Binding CommandWithNoArgs}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
Мы не можем получить доступ к EventArgs
события MouseEnter
через привязку, поэтому нам придется изменить часть, которая отбрасывает ее.
Как это бывает, эта часть является InvokeCommandAction
.
"Итак, мы просто собираемся подклассифицировать его и переопределить удобный метод, который ждал нас все время" - это то, что я хотел написать. Но класс запечатан.
Итак, нам придется подклассифицировать его родительский (абстрактный) класс: TriggerAction<DependencyObject>
Самая основная реализация:
public class InteractiveCommand : TriggerAction<DependencyObject>
{
protected override void Invoke(object parameter)
{
}
}
И это parameter
является вашим EventArgs
!
Но держитесь, это не так просто, мы должны воспроизвести поведение регулярного InvokeCommandAction
.
Через Reflector я декомпилировал его (но вы могли пойти посмотреть на официальный источник, я просто ленив).
Мы не будем заботиться о свойстве CommandParameter
dependency, мы будем предполагать, что если вы используете это вместо InvokeCommandAction
, вы действительно хотите EventArgs
каждый раз.
Здесь представлен полный класс (только WPF, см. EDIT для SilverLight):
public class InteractiveCommand : TriggerAction<DependencyObject>
{
protected override void Invoke(object parameter)
{
if (base.AssociatedObject != null)
{
ICommand command = this.ResolveCommand();
if ((command != null) && command.CanExecute(parameter))
{
command.Execute(parameter);
}
}
}
private ICommand ResolveCommand()
{
ICommand command = null;
if (this.Command != null)
{
return this.Command;
}
if (base.AssociatedObject != null)
{
foreach (PropertyInfo info in base.AssociatedObject.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance))
{
if (typeof(ICommand).IsAssignableFrom(info.PropertyType) && string.Equals(info.Name, this.CommandName, StringComparison.Ordinal))
{
command = (ICommand)info.GetValue(base.AssociatedObject, null);
}
}
}
return command;
}
private string commandName;
public string CommandName
{
get
{
base.ReadPreamble();
return this.commandName;
}
set
{
if (this.CommandName != value)
{
base.WritePreamble();
this.commandName = value;
base.WritePostscript();
}
}
}
#region Command
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Using a DependencyProperty as the backing store for Command. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(InteractiveCommand), new UIPropertyMetadata(null));
#endregion
}
Как и любой код, который вы извлекаете из Интернета, , я настоятельно рекомендую читать весь класс и пытаюсь понять, что он делает. Не просто бросайте его в свое приложение.
Теперь мы можем сделать:
<Button Content="I am a button">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<local:InteractiveCommand Command="{Binding CommandWithEventArgs}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
И код позади:
#region CommandWithEventArgs
DelegateCommand<MouseEventArgs> _CommandWithEventArgs;
/// <summary>
/// Exposes <see cref="CommandWithEventArgs(MouseEventArgs)"/>.
/// </summary>
public DelegateCommand<MouseEventArgs> CommandWithEventArgs
{
get { return _CommandWithEventArgs ?? (_CommandWithEventArgs = new DelegateCommand<MouseEventArgs>(CommandWithEventArgs)); }
}
#endregion
public void CommandWithEventArgs(MouseEventArgs param)
{
}
И что обертка;)
EDIT: Для SilverLight вместо этого используйте этот код:
public class InteractiveCommand : TriggerAction<DependencyObject>
{
protected override void Invoke(object parameter)
{
if (base.AssociatedObject != null)
{
ICommand command = Command;
if ((command != null) && command.CanExecute(parameter))
{
command.Execute(parameter);
}
}
}
#region Command
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
// Using a DependencyProperty as the backing store for Command. This enables animation, styling, binding, etc...
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(InteractiveCommand), new UIPropertyMetadata(null));
#endregion
}
Но учтите, что он менее безопасен, чем использование полноценной версии WPF (не проверяет типы, может сбой с замороженными элементами).