如何在silverlight中拖放“盒子”

我有一个像这样的盒子,现在我试图拖放盒子,用矩形和其他对象我做了,但有了这个我不知道该怎么办。

http://tinypic.com/r/24aydye/5

这是我如何做框的代码

XAML:

          

c#代码:

 public partial class MyBox : UserControl { public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register("Header", typeof(string), typeof(MyBox),null); public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Content", typeof(string), typeof(MyBox),null); public string Header { get { return GetValue(HeaderProperty) as string; } set { SetValue(HeaderProperty, value); } } public string Text { get { return GetValue(TextProperty) as string; } set { SetValue(TextProperty, value); } } public MyBox() { InitializeComponent(); this.DataContext = this; } 

这是添加另一个框的代码:

 private void Button_Click(object sender, RoutedEventArgs e) { panel.Children.Add(new MyBox { //LayoutRoot.Children.Add(new MyBox { Header = "Another box", Text = "...", // BorderBrush = Brushes.Black, BorderThickness = new Thickness(1), Margin = new Thickness(10) }); } 

这是一个示例,灵感来自https://stackoverflow.com/a/1495486/145757 (感谢Corey ),略微适应,简化(没有额外的布尔值)和增强(考虑边距考虑)我们的用例:

首先,我修改了盒子,使其具有专用的拖动区域:

             

MainWindow XAML略有修改:

            

拖放引擎在代码隐藏中:

 using System.Windows; using System.Windows.Media; using System.Windows.Input; using System.Windows.Controls; namespace WpfApplication1 { public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void Button_Click(object sender, RoutedEventArgs e) { MyBox box = new MyBox { Header = "Another box", Text = "...", BorderBrush = Brushes.Black, BorderThickness = new Thickness(1), Margin = new Thickness(10) }; box.MouseLeftButtonDown += Box_MouseLeftButtonDown; box.MouseLeftButtonUp += Box_MouseLeftButtonUp; box.MouseMove += Box_MouseMove; panel.Children.Add(box); } private MyBox draggedBox; private Point clickPosition; private void Box_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { draggedBox = sender as MyBox; clickPosition = e.GetPosition(draggedBox); draggedBox.CaptureMouse(); } private void Box_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { draggedBox.ReleaseMouseCapture(); draggedBox = null; } private void Box_MouseMove(object sender, MouseEventArgs e) { if (draggedBox != null) { Point currentPosition = e.GetPosition(panel); draggedBox.RenderTransform = draggedBox.RenderTransform ?? new TranslateTransform(); TranslateTransform transform = draggedBox.RenderTransform as TranslateTransform; transform.X = currentPosition.X - clickPosition.X - draggedBox.Margin.Left; transform.Y = currentPosition.Y - clickPosition.Y - draggedBox.Margin.Right; } } } } 

看看Blend Interaction行为。 我做了一段时间的样本http://invokeit.wordpress.com/2012/02/10/wp7-drag-drop-example/