【问题标题】:Binding an event to a command in a viewmodel将事件绑定到视图模型中的命令
【发布时间】: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


【解决方案1】:

您可以使用 blend sdk 中的 EventToCommand 行为

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" 


<DataGrid>
  <i:Interaction.Triggers>
     <i:EventTrigger EventName="MouseDoubleClick">
         <Commanding:EventToCommand  Command="{Binding Path=OpenCommand}" 
                                     CommandParameter="{Binding YourParameterBindingGoesHereIfYouNeedIt}"/>
       </i:EventTrigger>
   </i:Interaction.Triggers>

或者你看看 MVVMLight 也有这样的行为

【讨论】:

  • 这将是我的下一步,如果我找不到没有混合的解决方案
  • @blindmeis 你知道为什么 Commanding in Commanding:EventToCommand 变红 VS 抱怨不知道这部分吗?我使用了和你一样的命名空间。
  • 我从 Tools 获得了 SilverLight
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-10-25
  • 2011-09-01
  • 2022-01-09
  • 1970-01-01
  • 2012-10-02
  • 1970-01-01
  • 2013-01-16
相关资源
最近更新 更多