Saturday, September 11, 2010

Draggable Border in Silverlight

Sometimes it may be required to have draggable borders in Silverlight application.

In the XAML file create the definition for the Border.

Here is the XAML definition for Border.

==============================================

<!—Border Welcome -->
<Border x:Name="BorderWelcome" BorderBrush="Gray" BorderThickness="5" Width="180" Height="100" Background="Silver" VerticalAlignment="Top" HorizontalAlignment="Right" Margin="0,100,10,0" Visibility="Collapsed" CornerRadius="10" >
<Grid x:Name="GridWelcome" Height="90" Width="170">
<StackPanel>
</StackPanel>
</Grid>
</Border>

==============================================

In the C sharp code add this new class (BorderDragDrop) to the project.

==============================================
using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
namespace SilverlightGISApp
{
public class BorderDragDrop
{
Border border;
bool IsmouseDown = false;
TranslateTransform TTObject = new TranslateTransform();
Point originalWindowPoint;
bool getOrigWindowPosition = true;
private BorderDragDrop() { }
/// <summary>
/// Allow a Border to be dragged.
/// </summary>
public static void Attach(Border inborder)
{
BorderDragDrop bdd = new BorderDragDrop { border = inborder };
FrameworkElement theFrameworkElement = inborder as FrameworkElement;
theFrameworkElement.MouseLeftButtonDown += bdd.border_MouseLeftButtonDown ;
theFrameworkElement.MouseLeftButtonUp += bdd.border_MouseLeftButtonUp ;
theFrameworkElement.MouseMove += bdd.border_MouseMove ;
}

private void border_MouseMove(object sender, MouseEventArgs e)
{
FrameworkElement b = sender as FrameworkElement;
Point currntPoint = e.GetPosition(null);
if (IsmouseDown)
{
b.RenderTransform = TTObject;
TTObject.X = currntPoint.X - originalWindowPoint.X;
TTObject.Y = currntPoint.Y - originalWindowPoint.Y;
}
}

private void border_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
FrameworkElement b = sender as FrameworkElement;
b.ReleaseMouseCapture();
IsmouseDown = false;
border.Cursor = Cursors.Arrow;
}

private void border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
object origMouseDownSource = e.OriginalSource;
if (origMouseDownSource.GetType() != typeof(Border)) return;
FrameworkElement b = sender as FrameworkElement;
IsmouseDown = true;
if (getOrigWindowPosition == true)
{
originalWindowPoint = e.GetPosition(null);
getOrigWindowPosition = false;
}
b.CaptureMouse();
border.Cursor = Cursors.Hand;
}
}
}
==============================================

During the InitializeAppSettings() function call add the following line of code.

BorderDragDrop.Attach(BorderWelcome);

Now the border becomes draggable.

No comments:

Post a Comment

All Blogs so far ...