对多个对象使用相同的处理程序WPF C#

时间:2018-08-07 12:05:46

标签: c# wpf event-handling mouseevent

这是在图像上拖动一些裁切器的逻辑,并且可以工作。但是我在不同的窗口上有多个图像(由于文件不同),我想为所有图像分配相同的逻辑,但是我不想到处复制相同的代码。有什么办法吗?

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 个答案:

答案 0 :(得分:1)

您可以创建一个附加的行为。请参阅以下链接以获取有关此的更多信息。

WPF Attached Behavior Example – Watermark Text

Introduction to Attached Behaviors in WPF

Blend Behaviors

基本上有两种不同的方式来实现这类行为,通常称为附加行为和混合行为。如果您熟悉依赖项属性和附加属性,则附加行为只是附加了PropertyChangedCallback的附加属性,当该属性的值等于或附加DependencyObject时,附加属性将对其执行某些操作或扩展附加值。依赖项属性的更改。

与普通的附加行为相比,混合行为提供了更好的封装行为功能的方法。您可以通过创建从System.Windows.Interactivity.Behavior<T>类派生的类来定义Blend行为。您将需要添加对System.Windows.Interactivity的引用。

相关问题