我已像此链接一样以编程方式创建了InvokeCommandAction
event。
但是我不知道如何以编程方式创建以下事件,
<i:Interaction.Triggers>
<i:EventTrigger EventName="Drop">
<cmd:EventCommandExecuter Command="{Binding AddGridCommand}" />
</i:EventTrigger>
</i:Interaction.Triggers>
我已经尝试过如下操作,但是在EventCommandExecuter
命令中返回null。请任何人建议我实现这一目标。
void SetGridTrigger(Grid itemsControl, string bindingPath)
{
var binding = new Binding { Path = new PropertyPath(bindingPath) };
ICommand DropCommand = (binding as ICommand);
var eventCommandExecuter = new EventCommandExecuter { Command = DropCommand };
BindingOperations.SetBinding(eventCommandExecuter, InvokeCommandAction.CommandProperty, binding);
var eventTrigger = new System.Windows.Interactivity.EventTrigger { EventName = "Drop" };
eventTrigger.Actions.Add(eventCommandExecuter);
var triggers = Interaction.GetTriggers(itemsControl);
triggers.Add(eventTrigger);
}
EventCommandExecuter
public class EventCommandExecuter : TriggerAction<DependencyObject>
{
#region Constructors
public EventCommandExecuter()
: this(CultureInfo.CurrentCulture)
{
}
public EventCommandExecuter(CultureInfo culture)
{
Culture = culture;
}
#endregion
#region Properties
#region Command
public ICommand Command
{
get { return (ICommand)GetValue(CommandProperty); }
set { SetValue(CommandProperty, value); }
}
public static readonly DependencyProperty CommandProperty =
DependencyProperty.Register("Command", typeof(ICommand), typeof(EventCommandExecuter), new PropertyMetadata(null));
#endregion
#region EventArgsConverterParameter
public object EventArgsConverterParameter
{
get { return (object)GetValue(EventArgsConverterParameterProperty); }
set { SetValue(EventArgsConverterParameterProperty, value); }
}
public static readonly DependencyProperty EventArgsConverterParameterProperty =
DependencyProperty.Register("EventArgsConverterParameter", typeof(object), typeof(EventCommandExecuter), new PropertyMetadata(null));
#endregion
public IValueConverter EventArgsConverter { get; set; }
public CultureInfo Culture { get; set; }
#endregion
protected override void Invoke(object parameter)
{
var cmd = Command;
if (cmd != null)
{
var param = parameter;
if (EventArgsConverter != null)
{
param = EventArgsConverter.Convert(parameter, typeof(object), EventArgsConverterParameter, CultureInfo.InvariantCulture);
}
if (cmd.CanExecute(param))
{
cmd.Execute(param);
}
}
}
}
答案 0 :(得分:2)
您应将EventCommandExecuter.CommandProperty
绑定到绑定路径:
EventCommandExecuter eventCommandExecuter = new EventCommandExecuter();
BindingOperations.SetBinding(eventCommandExecuter, EventCommandExecuter.CommandProperty,
new Binding { Path = new PropertyPath(bindingPath) });
EventTrigger eventTrigger = new EventTrigger { EventName = "Drop" };
eventTrigger.Actions.Add(eventCommandExecuter);
Interaction.GetTriggers(itemsControl).Add(eventTrigger);