我目前有一个程序可以让我在画布(房间)周围移动不同的图像(家具),但是我想这样做,这样你只能在从列表框中选择家具时移动它们。我目前面临的问题是,每当我移动未选择的图像时程序就会冻结,这是由于UI线程太忙。这是代码:
private FurnitureImage draggedImage;
private Point mousePosition;
private bool ShouldMove = false;
private void CanvasRoomMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
var image = e.Source as FurnitureImage;
Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Input, new ThreadStart(() => {
try
{
if (image != null && CanvasRoom.CaptureMouse() && (Rooms[listBoxRooms.SelectedIndex].Furniture[listBoxFurniture.SelectedIndex].Equals(image)))
{
ShouldMove = true;
mousePosition = e.GetPosition(CanvasRoom);
draggedImage = image;
Panel.SetZIndex(draggedImage, 1);
//Thread.CurrentThread.Suspend();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.GetBaseException().ToString());
}
}));
}
private void CanvasRoomMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
if (draggedImage != null && ShouldMove)
{
CanvasRoom.ReleaseMouseCapture();
Panel.SetZIndex(draggedImage, 0);
draggedImage = null;
}
}
private void CanvasRoomMouseMove(object sender, MouseEventArgs e)
{
if (draggedImage != null && ShouldMove)
{
var position = e.GetPosition(CanvasRoom);
var offset = position - mousePosition;
mousePosition = position;
double NewXPos = Canvas.GetLeft(draggedImage) + offset.X;
double NewYPos = Canvas.GetTop(draggedImage) + offset.Y;
Rooms[listBoxRooms.SelectedIndex].Furniture[listBoxFurniture.SelectedIndex].XPos = NewXPos;
Rooms[listBoxRooms.SelectedIndex].Furniture[listBoxFurniture.SelectedIndex].YPos = NewYPos;
Canvas.SetLeft(draggedImage, NewXPos);
Canvas.SetTop(draggedImage, NewYPos);
}
}
FurnitureImage只是一个包含3个字段的图像:IsDraggable,XPos和YPos。我已经尝试为CanvasRoomMouseLeftButtonDown方法创建一个新线程但是这引发了一个异常,即该对象无法访问,因为它位于不同的线程上。我在网上环顾四周,发现了Dispatcher.Invoke(),但这并没有与新线程一起工作 - 程序继续冻结。有没有更好的方法来确保我可以移动的唯一图像是与列表框中选择的图像相对应的图像,以及如何修复多线程问题?