gpt4 book ai didi

wpf - 装饰元素上的装饰器和事件

转载 作者:行者123 更新时间:2023-12-04 18:52:28 24 4
gpt4 key购买 nike

我有一个自定义线形,它使用装饰器在该线的中间显示一个数组和一些文本。

alt text

问题是装饰元素的行为独立于装饰元素,并且不会将事件“转移”给它。在下面的代码中,我被迫手动将装饰元素重新链接到装饰元素( ta.MouseLeftButtonDown += Adorner_MouseLeftButtonDown; ),但不幸的是,即使这样也不起作用......
有人可以建议调用 this.OnMouseLeftButtonDown 时出了什么问题,为什么我没有收到相应的事件?

public class SegmentLine : Shape
{
AdornerLayer aLayer;

public static readonly DependencyProperty X1Property;
public static readonly DependencyProperty X2Property;
public static readonly DependencyProperty Y1Property;
public static readonly DependencyProperty Y2Property;
...

static SegmentLine() {
X1Property = DependencyProperty.Register("X1", typeof(double), typeof(SegmentLine), new FrameworkPropertyMetadata(double.NaN,
FrameworkPropertyMetadataOptions.AffectsRender));
X2Pro...
}

public SegmentLine()
: base()
{
this.Loaded += SegmentLine_Loaded;
}

void SegmentLine_Loaded(object sender, RoutedEventArgs e)
{
aLayer = AdornerLayer.GetAdornerLayer(this);
if (aLayer != null)
{
TextAdorner ta = new TextAdorner(this);
//ta.IsHitTestVisible = false;
ta.MouseLeftButtonDown += Adorner_MouseLeftButtonDown;
aLayer.Add(ta);
}
}

void Adorner_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
{
// !! try to rise the MouseLeftButtonDown event
this.OnMouseLeftButtonDown(e);
}

protected override void OnRender(DrawingContext drawingContext)
{
base.OnRender(drawingContext);
if (aLayer != null)
aLayer.Update();
}

class TextAdorner : Adorner
{
public TextAdorner(UIElement adornedElement)
: base(adornedElement) { }

protected override void OnRender(DrawingContext drawingContext)
{
// ADD LABEL ...
FormattedText ft = new FormattedText(...);
drawingContext.DrawText(ft, midPoint);

// Add ARROW ...
var myPathGeometry = new PathGeometry { Figures = myPathFigureCollection };
drawingContext.DrawGeometry(Brushes.Black, null, myPathGeometry);
}
}

protected override System.Windows.Media.Geometry DefiningGeometry
{
get
{
var geometryGroup = new GeometryGroup();
// Add line
geometryGroup.Children.Add(new LineGeometry(new Point(X1, Y1), new Point(X2, Y2)));
return geometryGroup;
}
}
}

最佳答案

您应该调用 this.RaiseEvent(e);而不是 this.OnMouseLeftButtonDown(e);将事件转移到装饰元素。
顺便说一句,您可以只使用一个事件处理程序来传输多种事件类型

void SegmentLine_Loaded(object sender, RoutedEventArgs e)
{
..
ta.MouseLeftButtonDown += Adorner_AnyEvent;
ta.MouseRightButtonDown += Adorner_AnyEvent;
}

void Adorner_AnyEvent(object sender, RoutedEventArgs e)
{
this.RaiseEvent(e);
}

关于wpf - 装饰元素上的装饰器和事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4214435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com