1

我有一个自定义元素类,它是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。

4

1 回答 1

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;
于 2013-01-26T08:21:52.933 回答