MVVM 和 Prism - 如何处理 ViewModel 中的 TextBox_DragEnter 和 TextBox_Drop 事件

MVVM and Prism - How to handle TextBox_DragEnter and TextBox_Drop Events in ViewModel

我正在学习 MVVM 和 PRISM 并尝试处理 TextBox 的 Drop 和 DragEnter 事件。

我已经通过单击按钮成功地做到了这一点

    public ButtonsViewModel()
    {
        //If statement is required for viewing the MainWindow in design mode otherwise errors are thrown
        //as the ButtonsViewModel has parameters which only resolve at runtime. I.E. events
        if (!(bool)DesignerProperties.IsInDesignModeProperty.GetMetadata(typeof(DependencyObject)).DefaultValue)
        {
            svc = ServiceLocator.Current;
            events = svc.GetInstance<IEventAggregator>();
            events.GetEvent<InputValidStatus>().Subscribe(SetInputStatus);
            StartCommand = new DelegateCommand(ExecuteStart, CanExecute).ObservesProperty(() => InputStatus);
            ExitCommand = new DelegateCommand(ExecuteExit);
        }
    }

    private bool CanExecute()
    {
        return InputStatus;
    }

    private void ExecuteStart()
    {
        InputStatus = true;
        ERA Process = new ERA();
        Proces.Run();
    }

这工作正常,并且对不采用 EventArgs 的其他事件执行此操作没有问题。所以 Drop 方法可以很好地实现,因为我不需要与 EventArgs 交互。

然而,对于 Textbox_DragEnter 事件,它会设置 TextBox 的 DragDropEffects

    private void TextBox_DragEnter(object sender, DragEventArgs e)
    {
        e.Effects = DragDropEffects.Copy;
    }

我的第一个想法是创建一个 ICommand 并将其绑定到 TextBox_DragEnter 事件,并在 ViewModel 中更新一个 DragDropEffects 属性。但是我看不到如何将效果绑定到文本框。

我可能想错了。这样做的正确方法是什么?

我知道我可以在后面的代码中轻松设置这些事件,但我不想这样做,而是纯粹使用 MVVM 模式

希望这是有道理的。

您可以使用交互事件触发器在视图模型中触发命令。例如下面我将命令 X 连接到 RowActivated 事件。这使用 MVVMLight EventToCommand 帮助程序。将此代码放入您的控件中

<i:Interaction.Triggers>
      <i:EventTrigger EventName="RowActivated">
           <commands:EventToCommand Command="{Binding X}" PassEventArgsToCommand="True"/>
      </i:EventTrigger>
</i:Interaction.Triggers>

您需要的命名空间是

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:commands="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras"

另一个交互触发器解决方案,类似于 Kevin 提出的方案,但这将适用于 Prism(非 MVVMLight 解决方案)。

需要命名空间:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"

XAML:

<TextBox Name="TextBox" Text="{Binding MVFieldToBindTo, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" >
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="DragEnter">
            <i:InvokeCommandAction 
                Command="{Binding BoundCommand}" 
                CommandParameter="{Binding Text, ElementName=TextBox}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</TextBox>

BoundCommand 将是视图模型中的 DelegateCommand。看起来你已经很清楚那是什么了。这是使用 DragEnter 编写的,但我在实践中只将其用于 LostFocus 事件,因此您可能需要稍微尝试一下。它应该让你朝着正确的方向前进。

查看 GongSolutions.WPF.DragDrop 以了解易于使用的支持 MVVM 的拖放框架。