[XAML]
<Window x:Class="WpfApplication2.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication2" Title="MainWindow" Height="350" Width="525" AllowDrop="True"><Grid AllowDrop="True" x:Name="mainGrd"><Grid Height="246" HorizontalAlignment="Left" AllowDrop="True" Margin="23,31,0,0" Name="grid1" VerticalAlignment="Top" Width="432" ShowGridLines="True" /><Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="190,108,0,0" Name="button1" VerticalAlignment="Top" Width="75"/></Grid></Window>
[C#]
public partial class MainWindow : Window { double m_MouseX; double m_MouseY; public MainWindow() { InitializeComponent(); button1.PreviewMouseUp += new MouseButtonEventHandler(button1_MouseUp); button1.PreviewMouseLeftButtonDown += new MouseButtonEventHandler(button1_MouseLeftButtonUp); button1.PreviewMouseMove += new MouseEventHandler(button1_MouseMove); } private void button1_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { m_MouseX = e.GetPosition(this).X; m_MouseY = e.GetPosition(this).Y; } private void button1_MouseMove(object sender, System.Windows.Input.MouseEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { e.MouseDevice.Capture(button1); System.Windows.Thickness _margin = new System.Windows.Thickness(); int _tempX = Convert.ToInt32(e.GetPosition(this).X); int _tempY = Convert.ToInt32(e.GetPosition(this).Y); _margin = mainGrd.Margin; if (m_MouseX > _tempX) { _margin.Left += (_tempX - m_MouseX); _margin.Right -= (_tempX - m_MouseX); } else { _margin.Left -= (m_MouseX - _tempX); _margin.Right -= (_tempX - m_MouseX); } if (m_MouseY > _tempY) { _margin.Top += (_tempY - m_MouseY); _margin.Bottom -= (_tempY - m_MouseY); } else { _margin.Top -= (m_MouseY - _tempY); _margin.Bottom -= (_tempY - m_MouseY); } mainGrd.Margin = _margin; m_MouseX = _tempX; m_MouseY = _tempY; } } private void button1_MouseUp(object sender, System.Windows.Input.MouseButtonEventArgs e) { e.MouseDevice.Capture(null); } }