我正在使用AlexeyZakharov 的博客中的 InvokeDelegateCommandAction 类,这是基于一些人的建议,即这是将参数从 View 发送回 EventTrigger 的 ViewModel 的最佳方式。
这就是我所拥有的。
在视图中(具体来说是一个 DataGrid):
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectionChanged" >
<cmnwin:InvokeDelegateCommandAction
Command="{Binding SelectedExcludedItemChangedCommand}"
CommandParameter="{Binding RelativeSource={RelativeSource self}, Path=SelectedItems}" />
</i:EventTrigger>
</i:Interaction.Triggers>
在视图模型中:
public DelegateCommandWithParameter SelectedActiveItemChangedCommand
{
get
{
return selectedActiveItemChangedCommand ??
(selectedActiveItemChangedCommand = new DelegateCommandWithParameter(DoSelectedActiveItemsChanged, CanDoSelectedActiveItemsChanged));
}
}
public bool CanDoSelectedActiveItemsChanged(object param)
{
return true;
}
public void DoSelectedActiveItemsChanged(object param)
{
if (param != null && param is List<Object>)
{
var List = param as List<Object>;
MyLocalField = List;
}
}
允许我将对象作为 args 传递的新型 DelegateCommand:
public class DelegateCommandWithParameter : ICommand
{
#region Private Fields
private Func<object, bool> canExecute;
private Action<object> executeAction;
private bool canExecuteCache;
#endregion
#region Constructor
public DelegateCommandWithParameter(Action<object> executeAction, Func<object, bool> canExecute)
{
this.executeAction = executeAction;
this.canExecute = canExecute;
}
#endregion
#region ICommand Members
public bool CanExecute(object parameter)
{
bool temp = canExecute(parameter);
if (canExecuteCache != temp)
{
canExecuteCache = temp;
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, new EventArgs());
}
}
return canExecuteCache;
}
public event EventHandler CanExecuteChanged;
public void Execute(object parameter)
{
executeAction(parameter);
}
#endregion
}
每当我的代码到达 DoSelectedActiveItemsChanged 时,arg 始终为 NULL....我在这里完全是个傻瓜吗?CommandParamter 在哪里链接到命令参数?AKA,为什么 View 没有将任何内容传递回命令?请帮忙。