Intersoft ClientUI Documentation
How-to: Drag an UIElement using API

This example shows how to drag an UIElement using API and store some data in the drag process.

Example

Description

You can use DragDrop.DoDragDrop method or ISDragDrop.DoDragDrop method to manually drag an UIElement. This method requires the UIElement to be dragged, the data its going to be carried (set it to null if there is none), and the drag effects. This example show you how to make an UIElement dragable and how to store the data to be carried.

Code

XAML
Copy Code
<Grid x:Name="LayoutRoot" Background="White">
    <StackPanel HorizontalAlignment="Center" VerticalAlignment="Center" MouseLeftButtonDown="StackPanel_MouseLeftButtonDown" MouseLeftButtonUp="StackPanel_MouseLeftButtonUp" MouseMove="StackPanel_MouseMove">
        <Image Source="folder.png" Height="64" Width="64"/>
        <TextBlock Text="My Archive" HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </StackPanel>
</Grid>
C#
Copy Code
private Point _startPosition;
private bool _isMouseLeftDown;        

public MainPage()
{
    // Required to initialize variables
    InitializeComponent();    
}

private void StackPanel_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    FrameworkElement element = sender as FrameworkElement;

    this._startPosition = e.GetPosition(null, true);
    this._isMouseLeftDown = true;

    element.CaptureMouse();
}

private void StackPanel_MouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
    FrameworkElement element = sender as FrameworkElement;

    this._startPosition = new Point(-1, -1);
    this._isMouseLeftDown = false;

    element.ReleaseMouseCapture();
}

private void StackPanel_MouseMove(object sender, System.Windows.Input.MouseEventArgs e)
{
    FrameworkElement element = sender as FrameworkElement;

    if (this._isMouseLeftDown)
    {
        Point current = e.GetPosition(null, true);

        if (Math.Abs(current.X - this._startPosition.X) >= 4 || Math.Abs(current.Y - this._startPosition.Y) >= 4)
        {
            DragDropEventData dataObject = new DragDropEventData();

            string sourceData = "Some string data to store...";
            byte[] unicodeText = Encoding.Unicode.GetBytes(sourceData); 
            byte[] utf8Text = Encoding.UTF8.GetBytes(sourceData);

            string uniCodeFormat = "Unicode";
            string utf8DataFormat = "UTF-8";
            
            dataObject.SetData(sourceData);            
            dataObject.SetData(uniCodeFormat, unicodeText);            
            dataObject.SetData(utf8DataFormat, utf8Text);

            this._isMouseLeftDown = false;
            DragDrop.DoDragDrop(element, dataObject, DragDropEffects.Move);
        }
    }
}
See Also

Concepts

Other Resources