Drag & Drop в Silverlight 3

Реализация Drag & Drop в Silverlight 3 стала еще проще. Создаем проект под Silverlight 3 и добавляем референс на сборку Microsoft.Expression.Interactivity, найти которую можно тут c:\Program Files\Microsoft Expression\Blend 3 Preview\Libraries\Silverlight\. Далее создаем класс унаследованный от Behavoir<> и переопределяем метод OnAttached.

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Expression.Interactivity;
namespace BlendWorld.Silverlight3.BehaviorsSample
{
    public class DragBehavior : Behavior<UIElement>
    {
        protected override void OnAttached()
        {
        }
    }
}

Далее в методе OnAttached необходимо назначить три новых обработчика событий мыши:

  • MouseIsDown
  • MouseIsUp
  • MouseIsMoving

У меня вышло примерно так:

using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Microsoft.Expression.Interactivity;
namespace BlendWorld.Silverlight3.BehaviorsSample
{
    public class DragBehavior : Behavior<UIElement>
    {
        private bool isDragging;
        private UIElement attachedElement;
        private UIElement parent;
        private Point lastPosition;
        protected override void OnAttached()
        {
            attachedElement = this.AssociatedObject;
            parent = Application.Current.RootVisual;
            attachedElement.MouseLeftButtonDown += MouseIsDown;
            attachedElement.MouseLeftButtonUp += MouseIsUp;
            attachedElement.MouseMove += MouseIsMoving;
        }
 
        private void MouseIsMoving(object sender, MouseEventArgs e)
        {
            if (isDragging)
            {
                Point currentPosition = e.GetPosition(parent);
                double dX = currentPosition.X - lastPosition.X;
                double dY = currentPosition.Y - lastPosition.Y;
                lastPosition = currentPosition;
                Transform oldTransform = attachedElement.RenderTransform;
                var rt = new TransformGroup();
                var newPos = new TranslateTransform
                                 {
                                     X = dX,
                                     Y = dY
                                 };
                if (oldTransform != null)
                {
                    rt.Children.Add(oldTransform);
                }
                rt.Children.Add(newPos);
                var mt = new MatrixTransform
                             {
                                 Matrix = rt.Value
                             };
               if (currentPosition.X < 0 || currentPosition.Y < 0)
                    return;
                attachedElement.RenderTransform = mt;
            }
        }
 
        private void MouseIsUp(object sender, MouseButtonEventArgs e)
        {
            isDragging = false;
            attachedElement.ReleaseMouseCapture();
        }
 
       private void MouseIsDown(object sender, MouseButtonEventArgs e)
        {
            isDragging = true;
            lastPosition = e.GetPosition(parent);
            attachedElement.CaptureMouse();
        }
    }
}

Теперь в XAML код добавляем необходимые неймспейсы и элемент для тестирования

<UserControl x:Class="BlendWorld.Silverlight3.BehaviorsSample.MainPage"
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml
    xmlns:interactivity="clr-namespace:Microsoft.Expression.Interactivity;assembly=Microsoft.Expression.Interactivity"
    xmlns:local="clr-namespace:BlendWorld.Silverlight3.BehaviorsSample"
   Width="400" Height="300">
    <Grid x:Name="LayoutRoot" Background="White">
        <Border Background="Gray" Width="150" Height="100" CornerRadius="5" BorderBrush="Black">
            <TextBlock Text="Drag Me..." HorizontalAlignment="Center" VerticalAlignment="Center"/>
            <interactivity:Interaction.Behaviors>
                <local:DragBehavior/>
            </interactivity:Interaction.Behaviors>
        </Border>
    </Grid>
</UserControl>

Запускаем и пробуем тягать

 

Живая демонстрация

Скачать исходный код: BlendWorld.Silverlight3.BehaviorsSample.zip (19,15 kb)


Метки: ,
Категории: Samples | Silverlight in Action

Комментарии закрыты

Об авторе

Name of author Григорий Полищук

.Net программист



Написать мне Send mail

Реклама

Рекомендую

Последние записи

Последние коментарии

Comment RSS

Статистика