1

我有一个如下定义的装饰器:

    private class ErrorAdorner : Adorner
    {
        private readonly Border _errorBorder;

        public ErrorAdorner(UIElement adornedElement)
            : base(adornedElement)
        {
            _errorBorder = new Border();
            _errorBorder.BorderThickness = new Thickness(2);
            _errorBorder.BorderBrush = Brushes.Red;
            Image img = new Image();
            img.HorizontalAlignment = HorizontalAlignment.Right;
            img.VerticalAlignment = VerticalAlignment.Center;
            img.Stretch = Stretch.None;
            Binding imgBinding = new Binding
            {
                Source = adornedElement,
                Path = new PropertyPath(IconProperty)
            };
            img.SetBinding(Image.SourceProperty, imgBinding);
            Binding ttBinding = new Binding
            {
                Source = adornedElement,
                Path = new PropertyPath(ErrorMessageProperty)
            };
            img.SetBinding(ToolTipProperty, ttBinding);
            _errorBorder.Child = img;
        }

        protected override Size MeasureOverride(Size constraint)
        {
            AdornedElement.Measure(constraint);
            return AdornedElement.RenderSize;
        }

        protected override Size ArrangeOverride(Size finalSize)
        {
            _errorBorder.Arrange(new Rect(finalSize));
            return finalSize;
        }

        protected override Visual GetVisualChild(int index)
        {
            if (index == 0)
                return _errorBorder;
            throw new ArgumentOutOfRangeException("index");
        }

        protected override int VisualChildrenCount
        {
            get
            {
                return 1;
            }
        }
    }

ErrorMessage并且是在封闭类 ( )Icon中声明的附加属性。ErrorProviderErrorMessage属性设置为非空值时,装饰器被添加到元素中。

我的问题是,虽然正确渲染了装饰器,ToolTip但当我将鼠标移到图像上时,图像上的 不会显示。我知道这不是绑定问题:当我使用 Snoop 检查控件时,我可以看到该ToolTip属性具有预期值。我怀疑这个问题与命中测试有关,因为我无法在装饰器中接收到任何与鼠标相关的事件......该IsHitTestVisible属性设置为 true,所以我不明白为什么我没有收到这些事件。

任何想法?

4

1 回答 1

3

好吧,这也是我以前咬过我的东西。当您定义自己的可视化树时,仅返回可视子级是不够的,您还需要告诉 WPF 您已添加它们。在构造函数的末尾添加以下内容:

this.AddVisualChild(_errorBorder);
this.AddLogicalChild(_errorBorder);

您还应该实现该LogicalChildren属性:

protected override System.Collections.IEnumerator LogicalChildren
{
    get 
    { 
        yield return _errorBorder;
    }
}

如果您有多个孩子,我会使用UIElementCollection. 它将它们添加到可视化和逻辑树中,您可以从LogicalChildrenVisualChildrenCountGetVisualChild覆盖中使用它。

于 2011-08-04T14:29:18.177 回答