私のアプリはwpf mvvmで、イベントにRelayCommand\EventToCommandバインディングを使用しています。私のアプリは、ListBox から ItemsControl への典型的なドラッグ アンド ドロップを行います (実際には、ItemsControl が上にあり、ドロップされた項目を保持しているイメージ コントロールです)。ListBox には、vm ObservableCollection が取り込まれます。また、ItemsControl は、ドロップした MyObj アイテムを挿入する ObservableCollection でもあります。
ListBox から項目をドラッグして、ItemsControl\image にドロップすると、すべて正常に動作します。PreviewMouseLeftButtonDownCommand では、System.Windows.Media.VisualTreeHelper を使用してビジュアル ツリーを再帰的に上に移動するので、ListBox からドラッグすると、ドラッグされている MyObj アイテムを見つけることができます。しかし、ItemsControl からアイテムをドラッグしようとすると、コードが機能しません。私が返すことができるのは、アイテム (ラベル) の DataTemplate 変換だけです。私の質問は次のとおりです。PreviewMouseLeftButtonDownCommand RelayCommand\EventToCommand が起動したときに、ItemsControl から選択したアイテムを取得するにはどうすればよいですか?
VM C#:
PreviewMouseLeftButtonDownCommand = new RelayCommand<MouseButtonEventArgs>(e =>
{
if (e.Source is ListBox)
{
// get dragged list box item
ListBox listBox = e.Source as ListBox;
ListBoxItem listBoxItem = VisualHelper.FindAncestor<ListBoxItem>((DependencyObject)e.OriginalSource);
// Find the data behind the listBoxItem
if (listBox == null || listBoxItem == null) return;
MyObj tag = (MyObj)listBox.ItemContainerGenerator.ItemFromContainer(listBoxItem);
// Initialize the drag & drop operation
DataObject dragData = new DataObject("myObj", tag);
DragDrop.DoDragDrop(listBoxItem, dragData, DragDropEffects.Move);
}
else if (e.Source is ItemsControl)
{
ItemsControl itemsControl = e.Source as ItemsControl;
object item = VisualHelper.FindAncestor<UIElement>((DependencyObject)e.OriginalSource);
if (itemsControl == null || item == null) return;
MyObj tag = (MyObj)itemsControl.ItemContainerGenerator.ItemFromContainer(item);
// Initialize the drag & drop operation
DataObject dragData = new DataObject("myObj", tagDragging);
DragDrop.DoDragDrop(item, dragData, DragDropEffects.Move);
}
});