Sometimes we need to extend the RadTreeView’s Drag’and’Drop abilities in order to accept external data from other applications or Windows.
In this post I will show you how to successfully drag and drop images from windows desktop / windows explorer to a RadTreeView located in a running WPF Application.
Imagine we want to make a tree that shows pictures and names of our favourite football teams and our favourite players in these teams.
How can we achieve this ?
We can first create some ViewModels: PlayerViewModel, TeamViewModel, LeagueViewModel that all inherit from BaseViewModel. The BaseViewModel will implement the INotifyPropertyChanged interface and will expose Name(string) and ImgSource(Uri) properties.
Then we will create three different templates for the different ViewModels and a template selector class : ItemTemplateSelector. It will select the different templates depending of the ViewModel`s type.
void PreparedItem_DragOver(object sender, DragEventArgs e) { var currentItemUndeMouse = sender as RadTreeViewItem; if (currentItemUndeMouse != null && !currentItemUndeMouse.IsSelected) { currentItemUndeMouse.IsSelected = true; currentItemUndeMouse.IsExpanded = true; } e.Handled = true; }var fileNames = ((DataObject)e.Data).GetFileDropList(); private void PreparedItem_Drop(object sender, DragEventArgs e) { var destinationItem = sender as RadTreeViewItem; var fileNames = ((DataObject)e.Data).GetFileDropList(); if (destinationItem != null) { foreach (var fileName in fileNames) { if (!(fileName.EndsWith(".jpeg") || fileName.EndsWith(".jpg") || fileName.EndsWith(".png"))) { MessageBox.Show("The dragged file is not png or jpg!", "Wrong operation", MessageBoxButton.OK, MessageBoxImage.Warning, MessageBoxResult.OK); e.Handled = true; return; } int startIndexOfname = fileName.LastIndexOf("\\"); int endIndexOfname = fileName.LastIndexOf("."); string name = fileName.Substring(startIndexOfname + 1, endIndexOfname - startIndexOfname - 1); if (destinationItem.Item is PlayerViewModel) { return; } else if (destinationItem.Item is TeamViewModel) { (destinationItem.Item as TeamViewModel).Players.Add( new PlayerViewModel() { Name = name, ImgSource = new Uri(fileName, UriKind.Absolute) ); } else { (destinationItem.Item as LeagueViewModel).Teams.Add( new TeamViewModel() { Name = name, ImgSource = new Uri(fileName, UriKind.Absolute) }); } destinationItem.IsExpanded = true; } e.Handled = true; } } Then we add some Players in the teams:
And here is the desired result:
=====================================================================
You can find the full source code of this applidcation and the used images below.
=====================================================================
Feel free to ask if you need additional info.
Hi, I'm Kiril and I'm the Product Manager of Telerik UI for Android, Windows Universal and Windows Phone. Feel free to ping me on +KirilStanoev or @KirilStanoev