Using same handlers for multiple objects WPF C#

不问归期 提交于 2019-12-11 15:19:20

问题


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;
    }

回答1:


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.



来源:https://stackoverflow.com/questions/51726402/using-same-handlers-for-multiple-objects-wpf-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!