Monday, January 30, 2012

WPF Custom Behavior

(1) Behavior is a gneric type <>, non-generic one has no public ctor
(2)  Need System.Interactivity.Dll from Blend SDK or MVVM light donwload

<Window x:Class="TestCustomBehavior.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525"
        xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
        xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"
        xmlns:local="clr-namespace:TestCustomBehavior"
         >
    <Grid>
        <TextBlock Background="LightBlue" Height="23" HorizontalAlignment="Left" Margin="134,140,0,0" Name="textBlock1" Text="Drag Me Around" VerticalAlignment="Top" >
            <i:Interaction.Behaviors>
                <local:DragBehavior></local:DragBehavior>
            </i:Interaction.Behaviors>
        </TextBlock>
    </Grid>
</Window>



namespace TestCustomBehavior
{
    public class DragBehavior : Behavior<UIElement>
    {
        Point startPosMouse, startPosElement; int i = 0;
        TranslateTransform trans = new TranslateTransform();
        protected override void OnAttached()
        {
            Window parent = Application.Current.MainWindow;
            AssociatedObject.RenderTransform = trans;
            AssociatedObject.MouseLeftButtonDown += (sender, e) =>
                {
                    if (i == 0)
                    {
                        startPosElement = AssociatedObject.TranslatePoint(new Point(), parent); i = 1;
                    }
                    startPosMouse = e.GetPosition(parent);
                    AssociatedObject.CaptureMouse();
                };
            AssociatedObject.MouseLeftButtonUp += (sender, e) =>
                {
                    AssociatedObject.ReleaseMouseCapture();
                };

            AssociatedObject.MouseMove += (sender, e) =>
                {
                    Vector diff = e.GetPosition(parent) - startPosElement;
                    if (AssociatedObject.IsMouseCaptured)
                    {
                        trans.X= diff.X;
                        trans.Y = diff.Y;
                    }

                };
        }
    }
}

No comments: