我的主窗口中有一個畫布控件,當單擊按鈕時,將圖像(從路徑)添加到畫布。使用WPF中的設置將子圖像添加到畫布#
添加這些圖像時,我需要能夠拖動這些圖像,這些圖像是通過xaml與mouseMove等添加的,但是由於點擊事件處理程序是在C#中完成的,因此如何添加這些設置在C#中使用XAML拖動等
- 不理想的動態添加圖像/形狀
<!-- see below for drag functionality -->
<!--
//these are the xaml settings
//MouseLeftButtonDown = "shape_MouseLeftButtonDown"
//MouseLeftButtonUp = "shape_MouseLeftButtonUp"
//MouseMove = "shape_MouseMove"
-->
<Rectangle x:Name="semiTrailer" Fill="Red" Height="100" Stroke="Black" Width="319" HorizontalAlignment="Left" VerticalAlignment="Bottom" Canvas.Left="48" Canvas.Top="220" MouseLeftButtonDown="shape_MouseLeftButtonDown" MouseLeftButtonUp="shape_MouseLeftButtonUp" MouseMove="shape_MouseMove"/>
單擊處理程序 - 如何添加移動,點擊這裏設置
個private void addSemiOnly_Click(object sender, RoutedEventArgs e)
{
try {
Image img;
img = new Image();
img.Source = new BitmapImage(new Uri(@"/NexansOlexProcessTools;component/Images/canvasImages/BTrailerOnlyTypeA.png", UriKind.Relative));
//these are the xaml settings
//MouseLeftButtonDown = "shape_MouseLeftButtonDown"
//MouseLeftButtonUp = "shape_MouseLeftButtonUp"
//MouseMove = "shape_MouseMove"
//sets height works!
img.Height = 60;
//how to also add
//these are the xaml settings
//MouseLeftButtonDown = "shape_MouseLeftButtonDown"
//MouseLeftButtonUp = "shape_MouseLeftButtonUp"
//MouseMove = "shape_MouseMove"
LayoutRoot.Children.Add(img);
}
catch (Exception drawError)
{
}
}
功能做拖拽功能 - 適用於XAML加帆布項目
private void shape_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
source = (UIElement)sender;
Mouse.Capture(source);
captured = true;
x_shape = Canvas.GetLeft(source);
x_canvas = e.GetPosition(LayoutRoot).X;
y_shape = Canvas.GetTop(source);
y_canvas = e.GetPosition(LayoutRoot).Y;
}
private void shape_MouseMove(object sender, MouseEventArgs e)
{
if (captured)
{
double x = e.GetPosition(LayoutRoot).X;
double y = e.GetPosition(LayoutRoot).Y;
x_shape += x - x_canvas;
Canvas.SetLeft(source, x_shape);
x_canvas = x;
y_shape += y - y_canvas;
Canvas.SetTop(source, y_shape);
y_canvas = y;
}
}
private void shape_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
Mouse.Capture(null);
captured = false;
}
img.MouseMove + =新MouseEventHandler(shape_MouseMove); img.MouseLeftButtonDown + = new MouseButtonEventHandler(shape_MouseLeftButtonDown); img.MouseLeftButtonUp + = new MouseButtonEventHandler(shape_MouseLeftButtonUp);不捕獲事件並且沒有激活阻止 – BENN1TH