How can I resolve performance issues when dragging a view under another view in WPF?
Currently, when working with WPF, I meet a problem that when I drag an Image over the content of a Label, it becomes very slow. I try to increase the width and height of Label then drag the image over the background of Label (where not contain content), it still working normally. But whenever the image is dragged over the content area of Label, dragging action becomes very slow. For source code of my testing project, you can get full source code in https://github.com/thanhbinh93-bn/wpf_drag_performance
Here is my testing project: I have a very simple window which contains an Imageview:
<Window x:Class="OverlapeTesting.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:OverlapeTesting"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid x:Name="container" Background="Red">
<Image
Source="background.png"
Width="145" Height="90"
HorizontalAlignment="Left"
VerticalAlignment="Top"
PreviewMouseLeftButtonDown="Image_PreviewMouseLeftButtonDown"
PreviewMouseMove="Image_PreviewMouseMove"
PreviewMouseUp="Image_PreviewMouseUp"
x:Name="dragImage"/>
</Grid>
</Window>
Then in code behind, I add about 10000 labels to the container grid.
public void AddLabels()
{
for (int i = 0; i < 10000; i++)
{
Label lb = new Label();
lb.Content = "WWW";
lb.Foreground = Brushes.White;
lb.FontSize = 20;
container.Children.Add(lb);
lb.Width = 300;
lb.Height = 150;
lb.Background = new SolidColorBrush(Colors.Green);
//lb.Opacity = 0.1;
}
}
The image can be dragged in the container grid by changing its margin as following:
private void Image_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
m_pointPressToImage = e.GetPosition((sender as FrameworkElement).Parent as FrameworkElement);
Mouse.Capture(dragImage);
}
private void Image_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
Point pCurrent = new Point();
pCurrent = e.GetPosition((sender as FrameworkElement).Parent as FrameworkElement);
double deltaX = (pCurrent.X - m_pointPressToImage.X);
double deltaY = (pCurrent.Y - m_pointPressToImage.Y);
Thickness margin = dragImage.Margin;
margin.Left += deltaX;
margin.Top += deltaY;
dragImage.Margin = margin;
m_pointPressToImage = pCurrent;
}
}
private void Image_PreviewMouseUp(object sender, MouseButtonEventArgs e)
{
Mouse.Capture(null);
}
When I drag the image in an empty area, it is very fast. But when I drag the image over the label content's area("WWW"), it becomes very slow.
How can I resolve this performance issues? Thanks in advance!