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

标签 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 并将其绑定(bind)到 TextBox_DragEnter 事件,并在 ViewModel 中更新 DragDropEffects 属性。但我不知道如何将效果绑定(bind)到文本框。

我的想法可能是错误的。执行此操作的正确方法是什么?

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

希望这是有道理的。

最佳答案

另一种交互触发解决方案,类似于 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 将是 View 模型中的 DelegateCommand。看起来你已经很清楚那是什么了。这是使用 DragEnter 编写的,但我在实践中只将其用于 LostFocus 事件,因此您可能需要稍微尝试一下。它应该会让你朝着正确的方向前进。

关于c# - MVVM 和 Prism - 如何处理 ViewModel 中的 TextBox_DragEnter 和 TextBox_Drop 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41300719/

相关文章:

c# - 从 linq 到 SQL 访问已处理的 DataContext

c# - 一个类用于两个 JSON 响应

c# - Entity Framework 有时不加载子对象/集合的内容

wpf - 集合和父/子关系的 MVVM 概念

entity-framework - 通用ViewModel

c# - WPF MVVM 我可以从 View 中使用模型吗

c# - Microsoft Outlook 将抄送添加到电子邮件

c# - 在 MVC EF 中使用高级属性的正确方法

c# - 在 WPF float 撕裂选项卡中托管 Win32 窗口

c# - 从全局X关闭按钮调用viewModel中定义的方法