从VisualTreeHelper.HitTest访问FrameworkElement的子类

时间:2013-01-26 06:05:39

标签: c# wpf .net-4.0 frameworkelement visualtreehelper

我有一个自定义元素类,它是FrameworkElement的子类。

public class MyCustomElement : FrameworkElement
{
    private VisualCollection children;

    public MyCustomElement()
    {
        this.children = new VisualCollection(this);
        this.children.Add(MyDrawingRoutines());
    }

    private DrawingVisual MyDrawingRoutines()
    {
        //...
    }

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

    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index >= children.Count)
        {
            throw new ArgumentOutOfRangeException();
        }

        return children[index];
    }
}

UI包含一个画布,其中添加了这些自定义绘图元素并执行了命中测试。

public partial class MainWindow : Window
{
        private MyCustomElement myCustomElement;

        public MainWindow()
        {
            InitializeComponent();

            myCustomElement = new MyCustomElement();
            myCanvas.Children.Add(myCustomElement);
        }

        private void myCanvas_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            System.Windows.Point pt = e.GetPosition((UIElement)sender);
            VisualTreeHelper.HitTest(this, null, new HitTestResultCallback(leftClickCallback), new PointHitTestParameters(pt));
        }

        public HitTestResultBehavior leftClickCallback(HitTestResult result)
        {
            if (result.VisualHit.GetType() == typeof(DrawingVisual))
            {
                if (((DrawingVisual)result.VisualHit).Opacity == 1.0)
                {
                    ((DrawingVisual)result.VisualHit).Opacity = 0.4;
                }
                else
                {
                    ((DrawingVisual)result.VisualHit).Opacity = 1.0;
                }
            }

            return HitTestResultBehavior.Stop;
        }

    }
}

此代码按预期工作,但我找不到一种方法来确定检测到的DrawingVisual属于哪个MyCustomElement。现在,不透明度调整只是表面上正确吗?我想更改MyCustomElement上的opacity属性,让MyDrawingRoutines()方法应用它,并且只在Canvas上绘制完成的DrawingVisual。

1 个答案:

答案 0 :(得分:2)

您应该能够将DrawingVisual的Parent属性强制转换为MyCustomElement类:

public HitTestResultBehavior leftClickCallback(HitTestResult result)
{
    var visual = result.VisualHit as DrawingVisual;

    if (visual != null)
    {
        var element = visual.Parent as MyCustomElement;

        if (element != null)
        {
            if (element.Opacity == 1.0)
            {
                element.Opacity = 0.4;
            }
            else
            {
                element.Opacity = 1.0;
            }
        }
    }

    return HitTestResultBehavior.Stop;
}

如果您需要获取任何视觉的父级(不仅仅是具有上述Parent属性的ContainerVisual),您可以使用VisualTreeHelper.GetParent

var visual = result.VisualHit;
var element = VisualTreeHelper.GetParent(visual) as MyCustomElement;