Click here to Skip to main content
15,919,931 members
Articles / Desktop Programming / WPF

How to make any UI element drag-able using Behaviors in WPF

Rate me:
Please Sign up or sign in to vote.
4.08/5 (5 votes)
29 Aug 2010CPOL 28.2K   3   3
in order to make your UI element drag-able without any extra code, all what you have to do is just selecting behaviors from Assets panel in Expression Blend then drag and drop the MouseDragElementBehavior to your UI element.
for example we will do this to a rectangle here you are the XAML code:

<Rectangle Fill="Red" Stroke="Black" Margin="230,218,172,132"> <br />
			<i:Interaction.Behaviors> <br />
				<il:MouseDragElementBehavior/> <br />
			</i:Interaction.Behaviors> <br />

don't forget to include these namespaces:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" xmlns:il="clr-namespace:Microsoft.Expression.Interactivity.Layout;assembly=Microsoft.Expression.Interactions"

if you are working with Blend, they will be placed automatically after setting the drag behavior, and if you are using Visual Studio you will need to set them manually


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Software Developer Asset Technology Group
Egypt Egypt
I'm a professional components designer, web developer, UX engineer and 3d designer as well, I'm 4 years experienced .net software engineer and 7 years experienced 3d designer using 3D Max. I'm very interested in RIA technologies, prototyping and UX engineering.

Ahmed Said
Senior .Net Software Engineer

Comments and Discussions

QuestionThank you Pin
André Canha1-Jul-12 7:02
André Canha1-Jul-12 7:02 
Generalthe drag behavior enables you to drag the element you want, ... Pin
Ahmed_Said31-Aug-10 1:34
Ahmed_Said31-Aug-10 1:34 
GeneralIt will only allow you to drag a UI Element inside its conta... Pin
Simon Dufour30-Aug-10 2:09
Simon Dufour30-Aug-10 2:09 
It will only allow you to drag a UI Element inside its container right? There's no validation, no way to control the other UI elements while you're dragging or anything like that. I'm asking because I think that if someone need some sort of complex drag behavior, I think this method wouldn't work. Aren't I right?

Interesting tip. Definitely a vote 4 for me. Would have given a 5 if it had a answer to the questions I've asked because I think it would be important to define the scope of the tip a bit better.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.