×
Namespaces

Variants
Actions
(Difference between revisions)

Drag & Drop in Windows Phone

From Nokia Developer Wiki
Jump to: navigation, search
pavan.pareta (Talk | contribs)
(Pavan.pareta -)
hamishwillee (Talk | contribs)
m (Hamishwillee - Addition to article of: Category:Windows Phone 7.5)
(19 intermediate revisions by 6 users not shown)
Line 1: Line 1:
[[Category:Windows Phone]][[Category:Silverlight]][[Category:Code Examples]][[Category:Code Snippet]]
+
[[Category:Windows Phone]][[Category:Silverlight]][[Category:Code Examples]][[Category:UI]]
{{Abstract|This article explains how use Interaction Behaviors API to Drag & Drop objects in Windows Phone }}
+
{{FeaturedArticle|timestamp=20121125}}
 
+
{{Abstract|This article explains how to use [http://msdn.microsoft.com/en-us/library/microsoft.expression.interactivity.layout.mousedragelementbehavior_members(v=expression.40).aspx Interaction Behaviors API] to Drag & Drop objects in Windows Phone }}
  
 
{{ArticleMetaData <!-- v1.2 -->
 
{{ArticleMetaData <!-- v1.2 -->
 
|sourcecode= [[Media:WmDev DragAndDrop.zip]]
 
|sourcecode= [[Media:WmDev DragAndDrop.zip]]
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
 
|installfile= <!-- Link to installation file (e.g. [[Media:The Installation File.sis]]) -->
|devices= Nokia Lumia 710
+
|devices= Nokia Lumia 710, 800
 
|sdk= Windows Phone 7.1
 
|sdk= Windows Phone 7.1
 
|platform= Windows Phone 7.5 (mango)
 
|platform= Windows Phone 7.5 (mango)
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
 
|devicecompatability= <!-- Compatible devices e.g.: All* (must have internal GPS) -->
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->  
+
|dependencies= <!-- Any other/external dependencies e.g.: Google Maps Api v1.0 -->
|signing=<!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
+
|signing= <!-- Signing requirements - empty or one of: Self-Signed, DevCert, Manufacturer -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
 
|capabilities= <!-- Capabilities required by the article/code example (e.g. Location, NetworkServices. -->
|keywords= <!-- APIs, classes and methods (e.g. QSystemScreenSaver, QList, CBase -->
+
|keywords= [http://msdn.microsoft.com/en-us/library/microsoft.expression.interactivity.layout.mousedragelementbehavior_members(v&#61;expression.40).aspx Interaction Behaviors API]
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|language= <!-- Language category code for non-English topics - e.g. Lang-Chinese -->
 
|translated-by= <!-- [[User:XXXX]] -->
 
|translated-by= <!-- [[User:XXXX]] -->
|translated-from-title= <!-- Title only -->  
+
|translated-from-title= <!-- Title only -->
 
|translated-from-id= <!-- Id of translated revision -->
 
|translated-from-id= <!-- Id of translated revision -->
|review-by=<!-- After re-review: [[User:username]] -->
+
|review-by= <!-- After re-review: [[User:username]] -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|review-timestamp= <!-- After re-review: YYYYMMDD -->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-by= <!-- After significant update: [[User:username]]-->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
 
|update-timestamp= <!-- After significant update: YYYYMMDD -->
|creationdate= <!-- Format YYYYMMDD -->
+
|creationdate= 20120916
|author= <!-- Display as link [[User:username]] -->
+
|author= [[User:Pavan.pareta]]
 
}}
 
}}
  
 
== Introduction ==
 
== Introduction ==
Drag & Drop is feature, which allows you to move object from one place to another place in your application. Drag and drop functionality also allows you to a smart user experience to access the application. This article shows how simple drag and drop can be implemented in Windows Phone.
 
  
== Implementation ==
+
There are three core sequences to be implemented in drag & drop using traditional process:
To create a new Windows Phone application, start Microsoft Visual Studio then create a new Project and select Windows Phone Application Template. I have named the application “WmDev_DragAndDrop”.
+
#  Tap (Press) & hold down – MouseDown Event.
 +
#  Drag the mouse to place the object to the desired location – MouseMove Event.
 +
#  Drop the object by releasing the mouse button - MouseUp Event.
  
In this example I have targeted both UI elements such as drawing objects i.e. (Rectangle, Ellipse and Path) and UI components (TextBlock, Image) to do Drag & Drop; however you can also use others components.
 
  
Here is an approach to achieve drag & drop functionality in your windows phone application.
+
In this example I have implemented the above drag'n'drop sequences using the Interaction Behaviors API. I have targeted both UI elements (drawing objects like Rectangle, Ellipse and Path etc) and UI components (TextBlock, Image). Note that you can also use other components.
  
==== Using managed API - Interaction Behaviors API ====
+
The animated gif below shows the running example.
<br />
+
[[File:WmDev DandD output.gif|frame|none|Output Screen]]
 
+
[[File:WmDev DandD concept.gif]]
+
 
+
Here is the three core sequence to implementation in drag & drop using traditional process.
+
 
+
#  Tap (Press) & hold down – MouseDown Event.
+
#  Drag the object to the desired location – MouseMove Event.
+
#  Drop the object by releasing the object - MouseUp Event.
+
  
 +
== Implementation ==
  
Using [http://msdn.microsoft.com/en-us/library/microsoft.expression.interactivity.layout.mousedragelementbehavior_members(v=expression.40).aspx Interaction Behaviors API] which is straightforward to implement and easy to use in your application.
+
Follow the steps mentioned to test the example, first create a new Windows Phone application. To do this start Microsoft Visual Studio then create a new Project and select Windows Phone Application Template. I have named the application “WmDev_DragAndDrop”.
  
 
'''Step-1:''' Add two references to '''Microsoft.Expression.Interactions''' and '''System.Windows.Interactivity''' in your solution.
 
'''Step-1:''' Add two references to '''Microsoft.Expression.Interactions''' and '''System.Windows.Interactivity''' in your solution.
  
#     Go to solution explorer and right click on Project '''->''' References '''->''' click on Add References…
+
# Go to solution explorer and right click on Project '''->''' References '''->''' click on Add References…
# In the Add Reference dialog box, select the .NET tab indicating the type of component you want to reference.
+
# In the '''Add Reference''' dialog box, select the .NET tab indicating the type of component you want to reference.
# Select the Microsoft.Expression.Interactions and System.Windows.Interactivity component to reference, and then click OK.
+
<!-- #: [[File:WmDevDnD0001.png|none]] -->
 
+
# Select the '''Microsoft.Expression.Interactions''' and '''System.Windows.Interactivity''' component to reference, and then click OK.
 
+
[[File:WmDevDnD0001.png]]
+
  
  
Line 69: Line 60:
  
 
'''Step-3:''' Define the following objects in XAML.
 
'''Step-3:''' Define the following objects in XAML.
 +
# [http://msdn.microsoft.com/en-us/library/system.windows.shapes.rectangle(v=vs.95).aspx Rectangle]
 +
# [http://msdn.microsoft.com/en-us/library/system.windows.shapes.ellipse(v=vs.95).aspx Ellipse]
 +
# [http://msdn.microsoft.com/en-us/library/system.windows.shapes.path(v=vs.95).aspx Path]
 +
# [http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock(v=vs.95).aspx TextBlock]
 +
# [http://msdn.microsoft.com/en-us/library/system.windows.controls.image(v=vs.95).aspx Image]
 +
  
# [http://msdn.microsoft.com/en-us/library/system.windows.shapes.rectangle(v=vs.95).aspx Rectangle]
 
# [http://msdn.microsoft.com/en-us/library/system.windows.shapes.ellipse(v=vs.95).aspx Ellipse]
 
# [http://msdn.microsoft.com/en-us/library/system.windows.shapes.path(v=vs.95).aspx Path]
 
# [http://msdn.microsoft.com/en-us/library/system.windows.controls.textblock(v=vs.95).aspx TextBlock]
 
# [http://msdn.microsoft.com/en-us/library/system.windows.controls.image(v=vs.95).aspx Image]
 
<br />
 
 
<code xml>
 
<code xml>
 
 
<Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="74" Margin="172,478,0,0" Stroke="Black" VerticalAlignment="Top" Width="76" />
 
<Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="74" Margin="172,478,0,0" Stroke="Black" VerticalAlignment="Top" Width="76" />
  
Line 95: Line 85:
  
  
'''Step-4:''' Attaching a '''MouseDragElementBehavior''' to the object and setting its '''ConstrainToParentBounds''' property to true/false, so it will respect the bounds of its Parent object like a Grid or Border or something. This example I have attached a '''ConstrainToParentBounds''' property as a false; now it’s only allows user to drag and drop within a parent’s restricted area.
+
'''Step-4:''' Attaching a {{Icode|MouseDragElementBehavior}} to the object and setting its {{Icode|ConstrainToParentBounds}} property to {{Icode|true}}/{{Icode|false}}, so it will respect the bounds of its parent object like a {{Icode|Grid}} or {{Icode|Border}} etc. In this example I have set the property {{Icode|ConstrainToParentBounds}} to {{Icode|false}}; now it only allows user to drag and drop within a parent’s restricted area.
  
 
<code xml>
 
<code xml>
 
+
<Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="74" Margin="172,478,0,0" Stroke="Black" VerticalAlignment="Top" Width="76" MouseMove="MouseMoving">
<Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="74" Margin="172,478,0,0" Stroke="Black" VerticalAlignment="Top" Width="76" MouseMove="MouseMoveing">
+
 
     <i:Interaction.Behaviors>
 
     <i:Interaction.Behaviors>
 
           <el:MouseDragElementBehavior ConstrainToParentBounds="False"/>
 
           <el:MouseDragElementBehavior ConstrainToParentBounds="False"/>
 
     </i:Interaction.Behaviors>
 
     </i:Interaction.Behaviors>
 
</Rectangle>
 
</Rectangle>
 
 
</code>
 
</code>
  
Here is completed XAML code:
+
Here is the complete XAML code:
 
<code xml>
 
<code xml>
 
<Grid x:Name="gd" Grid.Row="1" Margin="12,0,12,0">
 
<Grid x:Name="gd" Grid.Row="1" Margin="12,0,12,0">
  
            <Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="80" Margin="254,481,0,0" Stroke="Black" VerticalAlignment="Top" Width="102" MouseMove="MouseMoveing">
+
    <Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="80" Margin="254,481,0,0" Stroke="Black" VerticalAlignment="Top" Width="102" MouseMove="MouseMoving">
                <i:Interaction.Behaviors>
+
        <i:Interaction.Behaviors>
                    <el:MouseDragElementBehavior ConstrainToParentBounds="False"/>
+
            <el:MouseDragElementBehavior ConstrainToParentBounds="False"/>
                </i:Interaction.Behaviors>
+
        </i:Interaction.Behaviors>
            </Rectangle>
+
    </Rectangle>
  
            <Rectangle x:Name="rectangle2" Fill="#FFF3DF06" HorizontalAlignment="Right" Height="64" Margin="0,333,279,0" Stroke="Black" VerticalAlignment="Top" Width="123" MouseMove="MouseMoveing">
+
    <Rectangle x:Name="rectangle2" Fill="#FFF3DF06" HorizontalAlignment="Right" Height="64" Margin="0,333,279,0" Stroke="Black" VerticalAlignment="Top" Width="123" MouseMove="MouseMoving">
                <i:Interaction.Behaviors>
+
        <i:Interaction.Behaviors>
                    <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
+
            <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
                </i:Interaction.Behaviors>
+
        </i:Interaction.Behaviors>
            </Rectangle>
+
    </Rectangle>
  
            <Ellipse Margin="54,450,288,72" MouseMove="MouseMoveing" Fill="Blue">
+
    <Ellipse Margin="54,450,288,72" MouseMove="MouseMoving" Fill="Blue">
                <i:Interaction.Behaviors>
+
        <i:Interaction.Behaviors>
                    <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
+
            <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
                </i:Interaction.Behaviors>
+
        </i:Interaction.Behaviors>
            </Ellipse>
+
    </Ellipse>
  
            <Path Data="M78,318 L41,383 L111,380 z" Fill="#FFF306DF" HorizontalAlignment="Left" Height="71.5" Margin="70,0,0,438" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" VerticalAlignment="Bottom" Width="123" MouseMove="MouseMoveing" >
+
    <Path Data="M78,318 L41,383 L111,380 z" Fill="#FFF306DF" HorizontalAlignment="Left" Height="71.5" Margin="70,0,0,438" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" VerticalAlignment="Bottom" Width="123" MouseMove="MouseMoving" >
                <i:Interaction.Behaviors>
+
        <i:Interaction.Behaviors>
                    <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
+
            <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
                </i:Interaction.Behaviors>
+
        </i:Interaction.Behaviors>
            </Path>
+
    </Path>
  
            <Path Data="M275,309 L322,305 L357,327 L362,360 L342,391 L295,398 L259,376 L252,338 z" Fill="#FF06F30A" HorizontalAlignment="Right" Height="94" Margin="0,0,90.5,223" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" VerticalAlignment="Bottom" Width="111" MouseMove="MouseMoveing">
+
    <Path Data="M275,309 L322,305 L357,327 L362,360 L342,391 L295,398 L259,376 L252,338 z" Fill="#FF06F30A" HorizontalAlignment="Right" Height="94" Margin="0,0,90.5,223" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" VerticalAlignment="Bottom" Width="111" MouseMove="MouseMoving">
                <i:Interaction.Behaviors>
+
        <i:Interaction.Behaviors>
                    <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
+
            <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
                </i:Interaction.Behaviors>
+
        </i:Interaction.Behaviors>
            </Path>
+
    </Path>
  
            <TextBlock Height="30" Margin="70,50,250,133"
+
    <TextBlock Height="30" Margin="70,50,250,133"
              Name="textBlock1" Text="Pavan Pareta" MouseMove="MouseMoveing">
+
        Name="textBlock1" Text="Pavan Pareta" MouseMove="MouseMoving">
                <i:Interaction.Behaviors>
+
        <i:Interaction.Behaviors>
                    <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
+
            <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
 
                 </i:Interaction.Behaviors>
 
                 </i:Interaction.Behaviors>
            </TextBlock>
+
    </TextBlock>
  
            <Image Height="110" Name="image1" Stretch="Fill" Source="/WmDev_DragAndDrop;component/Images/house.png" Margin="254,90,95,407" MouseMove="MouseMoveing">
+
    <Image Height="110" Name="image1" Stretch="Fill" Source="/WmDev_DragAndDrop;component/Images/house.png" Margin="254,90,95,407" MouseMove="MouseMoving">
                <i:Interaction.Behaviors>
+
        <i:Interaction.Behaviors>
                    <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
+
            <el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
                </i:Interaction.Behaviors>
+
        </i:Interaction.Behaviors>
            </Image>
+
    </Image>
 
+
        </Grid>
+
  
 +
</Grid>
 
</code>
 
</code>
  
UI: Design view output
 
  
[[File:WmDevDnD0003.png]]
+
[[File:WmDevDnD0003.png|frame|none|UI: Design view output]]
 
+
<br />
'''Step-5:''' In additional I have attached an event '''(MouseMoveing)''' to all objects. Handled and set [http://msdn.microsoft.com/en-us/library/system.windows.controls.canvas.zindex(v=vs.95).aspx ZIndex] value to keep dragging object always on front of all objects.
+
'''Step-5:''' In addition i've attached an event '''({{Icode|MouseMoving}})''' to all objects. Handled and set [http://msdn.microsoft.com/en-us/library/system.windows.controls.canvas.zindex(v=vs.95).aspx ZIndex] value to keep dragging object always on front of all objects.
  
{{Note|<br />While drag an object to another one; that time a dragging object goes to behind of an object. To solve this issue, I have attached the ZIndex property to the current dragging object. <br /><br />ZIndex Property is an attached property, which allows you to explicitly set the z-order of objects in the child collection of Grid, Canvas and StackPanel objects.}}
+
{{Note|While dragging and placing an object over another; the dragged object get sets behind the other one. To resolve this issue, a property {{Icode|ZIndex}} may be to the object being dragged.
  
 +
{{Icode|ZIndex}} is an attached property, which allows you to explicitly set the z-order of objects in the child collection of {{Icode|Grid}}, {{Icode|Canvas}} and {{Icode|StackPanel}} objects.}}
  
Code Snippet for the MouseMoving method.
+
Code Snippet for the {{Icode|MouseMoving}} method.
 
<code csharp>
 
<code csharp>
private void MouseMoveing(object sender, MouseEventArgs e)
+
private void MouseMoving(object sender, MouseEventArgs e)
        {
+
{
 
             if (sender.GetType() == typeof(Rectangle))
 
             if (sender.GetType() == typeof(Rectangle))
 
             {
 
             {
Line 196: Line 183:
 
                 Canvas.SetZIndex(realSender, idx++);
 
                 Canvas.SetZIndex(realSender, idx++);
 
             }
 
             }
        }
+
}
  
 
</code>
 
</code>
Line 203: Line 190:
 
'''Step-6:''' Now run the application by pressing '''F5''' Key.
 
'''Step-6:''' Now run the application by pressing '''F5''' Key.
  
Output Screen
+
== References==
 
+
[[File:WmDev DandD output.gif]]
+
 
+
== Summary ==
+
 
+
'''References:'''
+
 
+
1. [http://msdn.microsoft.com/en-us/library/microsoft.expression.interactivity.layout.mousedragelementbehavior_members(v=expression.40).aspx MouseDragElementBehavior]
+
 
+
2. [http://msdn.microsoft.com/en-us/library/microsoft.expression.interactivity.layout.mousedragelementbehavior.constraintoparentbounds(v=expression.40).aspx MouseDragElementBehavior.ConstrainToParentBounds Property]
+
 
+
3. [http://msdn.microsoft.com/en-us/library/system.windows.controls.canvas.zindex(v=vs.95).aspx ZIndex]
+
  
 +
# [http://msdn.microsoft.com/en-us/library/microsoft.expression.interactivity.layout.mousedragelementbehavior_members(v=expression.40).aspx MouseDragElementBehavior]
 +
# [http://msdn.microsoft.com/en-us/library/microsoft.expression.interactivity.layout.mousedragelementbehavior.constraintoparentbounds(v=expression.40).aspx MouseDragElementBehavior.ConstrainToParentBounds Property]
 +
# [http://msdn.microsoft.com/en-us/library/system.windows.controls.canvas.zindex(v=vs.95).aspx ZIndex]
  
~ Happy Coding ~
+
== Sample Code ==
 +
You can download sample code from [[Media:WmDev DragAndDrop.zip]].
 +
 +
<!-- Translation --> [[zh-hans:Windows Phone的拖拽]][[Category:Windows Phone 7.5]]

Revision as of 08:15, 30 November 2012

Featured Article
25 Nov
2012

This article explains how to use Interaction Behaviors API to Drag & Drop objects in Windows Phone

WP Metro Icon UI.png
SignpostIcon XAML 40.png
SignpostIcon WP7 70px.png
Article Metadata
Code ExampleTested with
SDK: Windows Phone 7.1
Devices(s): Nokia Lumia 710, 800
Compatibility
Platform(s): Windows Phone 7.5 (mango)
Windows Phone 7.5
Article
Created: pavan.pareta (16 Sep 2012)
Last edited: hamishwillee (30 Nov 2012)

Contents

Introduction

There are three core sequences to be implemented in drag & drop using traditional process:

  1. Tap (Press) & hold down – MouseDown Event.
  2. Drag the mouse to place the object to the desired location – MouseMove Event.
  3. Drop the object by releasing the mouse button - MouseUp Event.


In this example I have implemented the above drag'n'drop sequences using the Interaction Behaviors API. I have targeted both UI elements (drawing objects like Rectangle, Ellipse and Path etc) and UI components (TextBlock, Image). Note that you can also use other components.

The animated gif below shows the running example.

Output Screen

Implementation

Follow the steps mentioned to test the example, first create a new Windows Phone application. To do this start Microsoft Visual Studio then create a new Project and select Windows Phone Application Template. I have named the application “WmDev_DragAndDrop”.

Step-1: Add two references to Microsoft.Expression.Interactions and System.Windows.Interactivity in your solution.

  1. Go to solution explorer and right click on Project -> References -> click on Add References…
  2. In the Add Reference dialog box, select the .NET tab indicating the type of component you want to reference.
  3. Select the Microsoft.Expression.Interactions and System.Windows.Interactivity component to reference, and then click OK.


Step-2: Add the following namespace at the top of your XAML file:

xmlns:el="clr-namespace:Microsoft.Expression.Interactivity.Layout;assembly=Microsoft.Expression.Interactions"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"


Step-3: Define the following objects in XAML.

  1. Rectangle
  2. Ellipse
  3. Path
  4. TextBlock
  5. Image


<Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="74" Margin="172,478,0,0" Stroke="Black" VerticalAlignment="Top" Width="76" />
 
<Rectangle x:Name="rectangle2" Fill="#FFF3DF06" HorizontalAlignment="Right" Height="64" Margin="0,333,279,0" Stroke="Black" VerticalAlignment="Top" Width="123" />
 
<Ellipse Margin="54,450,288,72" Fill="Blue"/>
 
<Path Data="M78,318 L41,383 L111,380 z" Fill="#FFF306DF" HorizontalAlignment="Left" Height="71.5" Margin="70,0,0,405.5" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" VerticalAlignment="Bottom" Width="123" />
 
<Path Data="M275,309 L322,305 L357,327 L362,360 L342,391 L295,398 L259,376 L252,338 z" Fill="#FF06F30A" HorizontalAlignment="Right" Height="94" Margin="0,0,90.5,223" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" VerticalAlignment="Bottom" Width="111" />
 
<TextBlock Height="30" Margin="70,50,250,133" Name="textBlock1" Text="Pavan Pareta" />
 
<Image Height="110" Name="image1" Stretch="Fill" Source="/WmDev_DragAndDrop;component/Images/house.png" Margin="254,90,95,407"/>


Step-4: Attaching a MouseDragElementBehavior to the object and setting its ConstrainToParentBounds property to true/false, so it will respect the bounds of its parent object like a Grid or Border etc. In this example I have set the property ConstrainToParentBounds to false; now it only allows user to drag and drop within a parent’s restricted area.

<Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="74" Margin="172,478,0,0" Stroke="Black" VerticalAlignment="Top" Width="76" MouseMove="MouseMoving">
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="False"/>
</i:Interaction.Behaviors>
</Rectangle>

Here is the complete XAML code:

<Grid x:Name="gd" Grid.Row="1" Margin="12,0,12,0">
 
<Rectangle x:Name="rectangle1" Fill="#FFF35206" HorizontalAlignment="Left" Height="80" Margin="254,481,0,0" Stroke="Black" VerticalAlignment="Top" Width="102" MouseMove="MouseMoving">
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="False"/>
</i:Interaction.Behaviors>
</Rectangle>
 
<Rectangle x:Name="rectangle2" Fill="#FFF3DF06" HorizontalAlignment="Right" Height="64" Margin="0,333,279,0" Stroke="Black" VerticalAlignment="Top" Width="123" MouseMove="MouseMoving">
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</i:Interaction.Behaviors>
</Rectangle>
 
<Ellipse Margin="54,450,288,72" MouseMove="MouseMoving" Fill="Blue">
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</i:Interaction.Behaviors>
</Ellipse>
 
<Path Data="M78,318 L41,383 L111,380 z" Fill="#FFF306DF" HorizontalAlignment="Left" Height="71.5" Margin="70,0,0,438" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" VerticalAlignment="Bottom" Width="123" MouseMove="MouseMoving" >
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</i:Interaction.Behaviors>
</Path>
 
<Path Data="M275,309 L322,305 L357,327 L362,360 L342,391 L295,398 L259,376 L252,338 z" Fill="#FF06F30A" HorizontalAlignment="Right" Height="94" Margin="0,0,90.5,223" Stretch="Fill" Stroke="Black" UseLayoutRounding="False" VerticalAlignment="Bottom" Width="111" MouseMove="MouseMoving">
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</i:Interaction.Behaviors>
</Path>
 
<TextBlock Height="30" Margin="70,50,250,133"
Name="textBlock1" Text="Pavan Pareta" MouseMove="MouseMoving">
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</i:Interaction.Behaviors>
</TextBlock>
 
<Image Height="110" Name="image1" Stretch="Fill" Source="/WmDev_DragAndDrop;component/Images/house.png" Margin="254,90,95,407" MouseMove="MouseMoving">
<i:Interaction.Behaviors>
<el:MouseDragElementBehavior ConstrainToParentBounds="True"/>
</i:Interaction.Behaviors>
</Image>
 
</Grid>


UI: Design view output


Step-5: In addition i've attached an event (MouseMoving) to all objects. Handled and set ZIndex value to keep dragging object always on front of all objects.

Note.pngNote: While dragging and placing an object over another; the dragged object get sets behind the other one. To resolve this issue, a property ZIndex may be to the object being dragged. ZIndex is an attached property, which allows you to explicitly set the z-order of objects in the child collection of Grid, Canvas and StackPanel objects.

Code Snippet for the MouseMoving method.

private void MouseMoving(object sender, MouseEventArgs e)
{
if (sender.GetType() == typeof(Rectangle))
{
Rectangle cx = (Rectangle)sender;
Canvas.SetZIndex(cx, idx++);
}
if (sender.GetType() == typeof(Ellipse))
{
Ellipse cx = (Ellipse)sender;
Canvas.SetZIndex(cx, idx++);
}
if (sender.GetType() == typeof(Path))
{
Path cx = (Path)sender;
Canvas.SetZIndex(cx, idx++);
}
else if (sender.GetType() == typeof(TextBlock))
{
TextBlock realSender = (TextBlock)sender;
Canvas.SetZIndex(realSender, idx++);
}
else if (sender.GetType() == typeof(Image))
{
Image realSender = (Image)sender;
Canvas.SetZIndex(realSender, idx++);
}
}


Step-6: Now run the application by pressing F5 Key.

References

  1. MouseDragElementBehavior
  2. MouseDragElementBehavior.ConstrainToParentBounds Property
  3. ZIndex

Sample Code

You can download sample code from Media:WmDev DragAndDrop.zip.

528 page views in the last 30 days.
×