WPF dragging within application throwing HRESULT E_FAIL from COM component
I have a few UserControls in my application which I need to support dragging and dropping from, so I extracted the code into an abstract class extending UserControl (code below). When I use this in one control which is part of a DataTemplate in a ListBox, everything works fine.
When I use it in the control which can also be the drop target, I get开发者_开发百科 the following exception on the DoDragDrop line:
COMException
Error HRESULT E_FAIL has been returned from a call to a COM component
This seems possibly related to WinForms interop, but I'm not using any WinForms or COM components - the application is pure WPF.
If I just continue execution, the drop happened successfully. If I surround the DoDragDrop call with a try block with empty catch block, everything seems to work as expected. I really don't want to ship code with this sort of a hack though.
public abstract class DraggableUserControl : UserControl
{
private Point? lastMouseDownPoint;
protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
{
base.OnMouseLeftButtonDown(e);
lastMouseDownPoint = e.GetPosition(this);
}
protected override void OnMouseMove(System.Windows.Input.MouseEventArgs e)
{
base.OnMouseMove(e);
if (e.LeftButton == MouseButtonState.Pressed && lastMouseDownPoint != null)
{
Point mousePosition = e.GetPosition(this);
if (((Point)lastMouseDownPoint - mousePosition).Length > 3)
{
BeginDrag();
}
}
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
if (e.LeftButton == MouseButtonState.Pressed && lastMouseDownPoint != null)
{
BeginDrag();
}
}
protected override void OnMouseUp(MouseButtonEventArgs e)
{
base.OnMouseUp(e);
if (e.ChangedButton == MouseButton.Left)
{
lastMouseDownPoint = null;
}
}
private void BeginDrag()
{
DataObject dragData = new DataObject(DragFormat, DragData);
//try
//{
DragDrop.DoDragDrop(this, dragData, DragDropEffects.Move);
//} catch {}
lastMouseDownPoint = null;
}
protected abstract String DragFormat
{ get; }
protected abstract Object DragData
{ get; }
protected abstract DragDropEffects DragAllowedEffects
{ get; }
}
A simple example created with your class seems to work just fine. I used a string and DragFormat of DataFormats.StringFormat. It worked just fine. Hans is right, there is no way to repro.
Im assuming whatever the Data object is , somehow mucks up the Get Data reflection or however it transfers it back.
My suggestion would be to break up your data object and see if any particular part has the same issue.
精彩评论