【问题标题】:Using same handlers for multiple objects WPF C#对多个对象使用相同的处理程序 WPF C#
【发布时间】:2023-03-31 00:03:01
【问题描述】:

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

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

【问题讨论】:

标签: c# wpf event-handling mouseevent


【解决方案1】:

您可以创建附加行为。请参阅以下链接了解更多信息。

WPF Attached Behavior Example – Watermark Text

Introduction to Attached Behaviors in WPF

Blend Behaviors

基本上有两种不同的方式来实现这些行为,通常称为附加行为和混合行为。如果您熟悉依赖属性和附加属性,则附加行为只是一个附加属性,其附加了一个PropertyChangedCallback,当依赖属性的值时,它执行一些操作或扩展它所附加的DependencyObject变化。

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

【讨论】:

    猜你喜欢
    • 2013-06-30
    • 2014-06-20
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    相关资源
    最近更新 更多