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

时间:2016-12-23 11:34:44

标签: c# wpf mvvm event-handling prism

我正在学习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模式保留它

希望这是有道理的。

3 个答案:

答案 0 :(得分:2)

另一个交互触发解决方案,类似于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事件,所以你可能不得不玩这个。它应该让你朝着正确的方向前进。

答案 1 :(得分:0)

您可以使用交互事件触发器在视图模型中触发命令。例如下面我将命令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"

答案 2 :(得分:0)

查看GongSolutions.WPF.DragDrop以获得易于使用的MVVM拖放框​​架。

相关问题