【发布时间】:2013-03-13 06:58:41
【问题描述】:
我已经在我的 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'。
请帮助。提前致谢。
【问题讨论】:
标签: xaml mvvm silverlight-5.0 icommand