如何将n的按钮从StackPanel拖放到画布 [英] How to drag n drop a button from stackpanel to canvas

查看:84
本文介绍了如何将n的按钮从StackPanel拖放到画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我想将按钮从堆栈面板n拖放到画布plz,请尽快帮助我...

Hi, I want to drag a button from stack panel n drop to canvas plz help me out asap...

谢谢

推荐答案

您应该基本上将Canvas的AllowDrop属性设置为true,并为StackPanel和画布的Drop事件.在MouseMove的处理程序中,您可以通过调用DragDrop.DoDragDrop来启动下拉操作 方法.这是一个基本的示例,应该可以使您了解:

You should basically set the AllowDrop property of the Canvas to true, and handle the MouseMove event for the StackPanel and the Drop event for the Canvas. In the handler for the MouseMove you initiate the drop down operation by calling the DragDrop.DoDragDrop method. Here is a basic example that should get you the idea:

public partial class MainWindow : Window
 {
  public MainWindow()
  {
   InitializeComponent();
  }

  private void Canvas_Drop(object sender, DragEventArgs e)
  {
   Canvas canvas = sender as Canvas;
   Button button = e.Data.GetData("myFormat") as Button;

   stackPanel.Children.Remove(btn); //remove button from StackPanel
   canvas.Children.Add(button); //add button to Canvas

   //reposition the button inside the Canvas by setting its Canvas.Left and Canvas.Top properties:
   Canvas.SetTop(btn, canvas.ActualHeight / 2 - btn.Height / 2);
   Canvas.SetLeft(btn, canvas.ActualWidth / 2 - btn.Width / 2);

  }

  private void StackPanel_MouseMove(object sender, MouseEventArgs e)
  {
   DependencyObject element = Mouse.DirectlyOver as DependencyObject;
   if(element != null && (element == btn || FindVisualParent<Button>(element) == btn))
   {
    DataObject dragData = new DataObject("myFormat", btn);
    DragDrop.DoDragDrop(stackPanel, dragData, DragDropEffects.Move);
   }
  }

  public static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
  {
   DependencyObject parentObject = VisualTreeHelper.GetParent(child);

   if (parentObject == null)
   return null;

   T parent = parentObject as T;
   if (parent != null)
    return parent;
   else
    return FindVisualParent<T>(parentObject);
  }
 }


<Window x:Class="WpfApplicationDd.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel>
        
  <StackPanel x:Name="stackPanel" MouseMove="StackPanel_MouseMove">
   <Button x:Name="btn" Content="Button" Width="50" Height="20"></Button>
  </StackPanel>

  <Canvas AllowDrop="True" Drop="Canvas_Drop"
   Background="Yellow" Width="100" Height="100">
  </Canvas>

    </StackPanel>
</Window>

请记住将任何有帮助的答复标记为答案和/或有帮助,也请记住,新问题应有新线索.

Please remember to mark any helpful replies as answer and/or helpful and also please remember that a new question deserves a new thread.


这篇关于如何将n的按钮从StackPanel拖放到画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆