初學者在這裏。WPF從列表框中拖放對象
我試圖創建一個用戶控件與在其他控制一個列表框,我想這個列表框允許拖放到該用戶控件的其他類似的實例。
這是另一個我想拖動對象,從一個列表框下拉:
[Serializable]
public class ListBoxFileName : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
private string FileNameValue;
public string FileName
{
get { return this.FileNameValue; }
set
{
if (value != this.FileNameValue)
{
this.FileNameValue = value;
NotifyPropertyChanged("FileName");
}
}
}
private bool FileIsSelectedValue;
public bool FileIsSelected
{
get { return this.FileIsSelectedValue; }
set
{
if (value != this.FileIsSelectedValue)
{
this.FileIsSelectedValue = value;
NotifyPropertyChanged("FileIsSelected");
}
}
}
}
這裏是我如何處理拖放:
private ListBoxItem _dragged;
private void FileNameList_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
if (_dragged != null)
return;
UIElement element = FileNameList.InputHitTest(e.GetPosition(FileNameList)) as UIElement;
while (element != null)
{
if (element is ListBoxItem)
{
_dragged = (ListBoxItem)element;
break;
}
element = VisualTreeHelper.GetParent(element) as UIElement;
}
}
private void Window_MouseMove(object sender, MouseEventArgs e)
{
if (_dragged == null)
return;
if (e.LeftButton == MouseButtonState.Released)
{
_dragged = null;
return;
}
DataObject obj = new DataObject(DataFormats.Serializable, _dragged);
DragDrop.DoDragDrop(_dragged, obj, DragDropEffects.All);
}
private void FileNameList_DragEnter(object sender, DragEventArgs e)
{
if (_dragged == null || e.Data.GetDataPresent(DataFormats.Serializable, true) == false)
e.Effects = DragDropEffects.None;
else
e.Effects = DragDropEffects.All;
}
private void FileListBox_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop, true))
{
string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
for (var i = 0; i < droppedFilePaths.Length; i++)
{
ListBoxFileName filename = new ListBoxFileName();
filename.FileName = droppedFilePaths[i];
filename.FileIsSelected = false;
FileNamesItems.Add(filename);
}
}
if (e.Data.GetDataPresent(DataFormats.Serializable, true))
{
ListBoxFileName BoxItem = new ListBoxFileName();
BoxItem = e.Data.GetData(DataFormats.Serializable) as ListBoxFileName;
}
}
一切除了當細發生丟棄事件,BoxItem
由於某種原因始終爲空,因此沒有任何內容添加到列表框中。
任何提示?
謝謝
你試過從https://www.nuget.org/packages/gong-wpf-dragdrop/鑼WPF-的DragDrop?源代碼也awailable,所以你可以看看它是如何實現的 – bamanow
@bamanow,的的NuGet鑼WPF取決於WPFToolkit包,這個包依賴於.NET 3.5。它與.NET 4.0或更高版本不兼容。 –
@Eriawan你錯了,而不是與.NET 4.0開始就沒有任何依賴性 – bamanow