对多个对象使用相同的处理程序WPF C# [英] Using same handlers for multiple objects WPF C#

查看:80
本文介绍了对多个对象使用相同的处理程序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附加行为示例–水印文本

WPF中的附加行为简介

混合行为

基本上有两种不同的方式来实现这类行为,通常称为附加行为和混合行为.如果您熟悉依赖项属性和附加属性,则附加行为就是附加了PropertyChangedCallback的附加属性,当依赖项属性的值时,附加属性会对附加的DependencyObject执行某些操作或扩展附加属性DependencyObject变化.

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.

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

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.

这篇关于对多个对象使用相同的处理程序WPF C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆