【发布时间】:2014-11-08 20:13:41
【问题描述】:
我刚开始编写自己的小型状态图编辑器。我希望它采用 MVVM 模式。 但是我在将事件绑定到视图模型中的命令时遇到了问题。
运行我的应用程序时,会出现此 InvalidCastException。
System.InvalidCastException:无法将“System.Reflection.RuntimeEventInfo”类型的对象转换为“System.Reflection.MethodInfo”类型。
我的 xaml 文件中有以下 sn-p。
<UserControl.Resources>
<vm:StateViewModel x:Key="StateViewModel"/>
</UserControl.Resources>
<Grid DataContext="{StaticResource StateViewModel}">
<Rectangle MouseLeftButtonDown="{Binding Path=DragStartCommand}">
</Grid>
在我的 StateViewModel 中,我创建了 ICommand 属性。
private DelegateCommand _dragStartCommand;
public ICommand DragStartCommand
{
get
{
if (_dragStartCommand == null)
{
_dragStartCommand = new DelegateCommand(StartDragging);
}
return _dragStartCommand;
}
}
private void StartDragging(object obj)
{
// ...
}
DelegateCommand 类如下所示
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
希望您能帮我解决问题。 为此,很高兴知道如何将 EventArgs 传递给我的命令并使用它们。
【问题讨论】:
-
错误发生在哪里,在哪一行?
-
它出现在我的 UserControl 的根标签中
标签: c# wpf mvvm binding command