简体   繁体   中英

Using same handlers for multiple objects WPF C#

This is logic for dragging some cropper over image, and it works. But i have multiple images on different windows (and because of that different files) and I want to assign same logic to all of them, but i dont want to copy same code everywhere. Is there any way to do it?

private bool isDragging;
private Point clickPosition;

    private void OnMouseMove(object sender, MouseEventArgs e)
    {
        if (isDragging)
        {
            Point currentPosition = e.GetPosition(this.Parent as UIElement);
            double xdiff = currentPosition.X - clickPosition.X;
            double ydiff = currentPosition.Y - clickPosition.Y;
            croppingAdorner.HandleThumb(1, 1, 0, 0, xdiff, ydiff);
            clickPosition = e.GetPosition(this);
        }
    }

    private void OnMouseDown(object sender, MouseButtonEventArgs e)
    {
        if (CropHelper.IsPointInsideRect(e.GetPosition(this.originalImage), rc))
        {
            isDragging = true;
            clickPosition = e.GetPosition(this);
        }
    }

    private void OnMouseUp(object sender, MouseButtonEventArgs e)
    {
        isDragging = false;
    }

    private void OnMouseLeave(object sender, MouseEventArgs e)
    {
        isDragging = false;
    }

You could create an attached behaviour. Please refer to the following links for more information about this.

WPF Attached Behavior Example – Watermark Text

Introduction to Attached Behaviors in WPF

Blend Behaviors

There are basically two different ways of implementing these kind of behaviours, commonly referred to as attached behaviours and Blend behaviours. If you are familiar with dependency properties and attached properties, an attached behaviour is simply an attached property with a PropertyChangedCallback attached to it that performs some action on or extends the DependencyObject to which it is attached when the value of the dependency property changes.

A Blend behaviour provides a better way of encapsulating the functionality of a behaviour compared to an ordinary attached behaviour. You define a Blend behaviour by creating a class that derives from the System.Windows.Interactivity.Behavior<T> class. You will need to add a reference to System.Windows.Interactivity .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM