LoginSignup
2
2

More than 5 years have passed since last update.

MvvmCrossでDrag&Dropイベントを処理

Posted at

Problem

WPFで作っているのはデスクトップアプリなので,Drag&Dropさせたい。というかDropされたファイルなりなんなりを処理したい。
しかしDragEventArgsを受け取るMvxCommandをViewModelに書いてしまうとWindows以外でビルドが通らなくなる上にそもそもPCLでは無理。ちなみにWPFオンリーであれば以下のような書き方ができます。

MvxCommandWithDragEventArgs
private MvxCommand<DragEventArgs> _itemDroppedCommand;
public ICommand ItemDroppedCommand
{
    get
    {
        return _itemDroppedCommand ??
                (_itemDroppedCommand =
                    new MvxCommand<DragEventArgs>(e => ItemDropped(e)));
    }
}

private void ItemDropped(DragEventArgs e)
{
    // Do something.
}

Solution

泣く泣くViewに書きます。今回はファイルパスを受け取ってみます。
まずはコマンドの定義。

DropViewModel.cs
private MvxCommand<string[]> _itemDroppedCommand;
public ICommand ItemDroppedCommand
{
    get
    {
        return _itemDroppedCommand ??
                (_itemDroppedCommand = new MvxCommand<string[]>(ExecItemDroppedCommand));
    }
}

private void ExecItemDroppedCommand(string[] items)
{
    // Do something.
}

WPFではView.csにDropイベントを実装。

View.cs
private void Dropped(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(DataFormats.FileDrop, false) return;
    var vm = this.ViewModel as DropViewModel;
    if (vm == null) return;
    vm.ItemDroppedCommand.Execute(e.Data.GetData(DataFormats.FileDrop));
}

Macでは…準備中

Conclusion

漂う無理矢理感。
もっといい方法があるのでは…?

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2