WPF:在Canvas的PreviewMouseLeftButtonDown中获取adorner中的底层元素

时间:2014-04-23 21:24:22

标签: wpf event-handling adorner

Canvas包含带装饰的元素。 Adorner使用VisualCollection,并将拇指放置在装饰元素的特定位置。我想点击画布的adorner,hanlde PreviewMouseLeftButtonDown事件,并获取装饰者内部的底层元素。但在这种情况下,我将MainWindow作为e.Source。能否请你帮忙?我几乎是WPF的新手。

public class ConnectorAdorner : Adorner
{
    private readonly ConnectorThumb _thumb;
    private readonly VisualCollection _visuals;

    public ConnectorAdorner(UIElement adornedElement) : base(adornedElement)
    {
        Focusable = true;
        _visuals = new VisualCollection(this);
        _thumb = new ConnectorThumb();
        _thumb.Background = Brushes.Transparent;
        _visuals.Add(_thumb);
    }

    protected override Size ArrangeOverride(Size finalSize)
    {
        double elHeight = AdornedElement.DesiredSize.Height;
        double adornerWidth = DesiredSize.Width;
        double adornerHeight = DesiredSize.Height;
        _thumb.Arrange(new Rect(0, -elHeight/2, adornerWidth, adornerHeight));
        return finalSize;
    }

    protected override Visual GetVisualChild(int index)
    {
        return _visuals[index];
    }

    protected override int VisualChildrenCount
    {
        get { return _visuals.Count; }
    }
}

public class Shape : UserControl
{
    private AdornerLayer _adornerLayer;

    public Shape()
    {
        Width = 50;
        Height = 50;
        Background = Brushes.Tomato;
        BorderThickness = new Thickness(2);
        BorderBrush = Brushes.Black;
        this.Loaded += OnLoaded;
    }

    private void OnLoaded(object sender, RoutedEventArgs routedEventArgs)
    {
        _adornerLayer = AdornerLayer.GetAdornerLayer(this);
        if (_adornerLayer != null)
        {
            ConnectorAdorner adorner = new ConnectorAdorner(this);
            _adornerLayer.Add(adorner);
        }
    }
}

public class ConnectorThumb : Thumb
{
    public ConnectorThumb()
    {
        Width = 20;
        Height = 20;
        Background = Brushes.Transparent;
        Foreground = Brushes.Black;
        BorderThickness = new Thickness(1);
        IsHitTestVisible = true;
    }
}

public partial class MainWindow : Window
{
    private void OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        // I'd like to get ConnectionThumb here..
    }
}

1 个答案:

答案 0 :(得分:0)

虽然很难说没有看到你的代码,但我认为在元素(Adorner)上使用Canvas.ZIndex属性将确保元素按照你想要的方式分层。