我已经在我的 mvvm 架构中将 Icommand 实现为 SimpleCommand.cs
public class SimpleCommand<T1, T2> : ICommand
{
private Func<T1, bool> canExecuteMethod;
private Action<T2> executeMethod;
public SimpleCommand(Func<T1, bool> canExecuteMethod, Action<T2> executeMethod)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = canExecuteMethod;
}
public SimpleCommand(Action<T2> executeMethod)
{
this.executeMethod = executeMethod;
this.canExecuteMethod = (x) => { return true; };
}
public bool CanExecute(T1 parameter)
{
if (canExecuteMethod == null) return true;
return canExecuteMethod(parameter);
}
public void Execute(T2 parameter)
{
if (executeMethod != null)
{
executeMethod(parameter);
}
}
public bool CanExecute(object parameter)
{
return CanExecute((T1)parameter);
}
public void Execute(object parameter)
{
Execute((T2)parameter);
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
并在我的 viewModel 中实现了这个 ICommand 如下:
private ICommand printCommand;
public ICommand PrintCommand
{
get { return printCommand; }
set { printCommand = value; }
}
myviewmodel() // in Constructor of ViewModel
{
this.PrintCommand = new SimpleCommand<Object, EventToCommandArgs>(ExecutePrintCommand);
}
}
在 XAML 上:我调用了 Command="{Binding PrintCommand}"
<Button Content="Print Button" Command="{Binding PrintCommand}" Width="120" Height="25" Margin="3"></Button>
它完美地工作......
但是当我尝试将 CommandParameter 发送到 Command As 时:
<Button Content="Print Button" Command="{Binding PrintCommand}" Width="120" Height="25" Margin="3" CommandParameter="{Binding ElementName=grdReceipt}"></Button>
然后命令没有执行。并给出错误:
无法将“System.Windows.Controls.Grid”类型的对象转换为“PropMgmt.Shared.EventToCommandArgs”类型。
请帮助。在此先感谢。