Friday, August 27, 2010

Make any UI element drag-able in WPF using behaviors

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"><i:Interaction.Behaviors>
<il:MouseDragElementBehavior/> </i:Interaction.Behaviors>
</Rectangle>

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 Expression 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

No comments: