Tim Huffam

Dotting the I and crossing the T of I.T.

  Home  |   Contact  |   Syndication    |   Login
  153 Posts | 0 Stories | 2415 Comments | 653 Trackbacks

News

Archives

Post Categories

Interesting Blogs/Links

Wednesday, November 05, 2008 #

The following code shows you how you can make Silverlight controls/objects moveable by dragging them with the mouse.
Page.cs:
<UserControl x:Class="MovingObjs.Page"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="400" Height="300">
    <Canvas x:Name="LayoutRoot" Background="White">
        <Border CornerRadius="10" x:Name="brdMovable" BorderBrush="Black" BorderThickness="2" Background="AntiqueWhite" Canvas.Top="100" Canvas.Left="10" MouseLeftButtonDown="brdMovable_MouseLeftButtonDown" MouseLeftButtonUp="brdMovable_MouseLeftButtonUp" MouseMove="brdMovable_MouseMove">
            <Grid x:Name="grid1" Width="300" Margin="5" >
                <TextBlock x:Name="txtBlkTest" Text="Test"></TextBlock>
            </Grid>
        </Border>
    </Canvas>
</UserControl>
Page.xaml.cs:
namespace MovingObjs
{
    public partial class Page : UserControl
    {
        private bool moving = false;
        private double offSetX;
        private double offSetY;
 
        public Page()
        {
            InitializeComponent();
        }
 
        private void brdMovable_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            moving = true;
            Point offset = e.GetPosition(brdMovable);
            offSetX = offset.X;
            offSetY = offset.Y;
        }
        private void brdMovable_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            moving = false;
        }
 
        private void brdMovable_MouseMove(object sender, MouseEventArgs e)
        {
            if (moving)
            {
                Canvas parent = (Canvas)this.brdMovable.Parent;
                Point p = e.GetPosition(parent);
                double x = p.X - offSetX;
                double y = p.Y - offSetY;
 
                txtBlkTest.Text = "X: " + x.ToString() + ", Y: " + y.ToString();
 
                this.brdMovable.SetValue(Canvas.LeftProperty, x);
                this.brdMovable.SetValue(Canvas.TopProperty, y);
            }
        }
    }
}