1
public class VisualCue : FrameworkElement
{
    public List<Indicator> Indicators { get; set; }

    public VisualCue()
    {
        this.Indicators = new List<Indicator>();
    }

    protected override int VisualChildrenCount
    {
        get { return this.Indicators.Count; }
    }

    protected override Visual GetVisualChild(int index)
    {
        return this.Indicators[index];
    }
}

public class Indicator : FrameworkElement
{
    protected override void OnRender(DrawingContext context)
    {
        context.DrawEllipse(Brushes.Red, 
            new Pen(Brushes.Black, 2), new Point(0, 0), 10, 10);

        base.OnRender(context);
    }
}

在 XAML 中:

<local:VisualCue x:Name="visualCue">
 <local:VisualCue.Indicators>
  <local:Indicator />
 </local:VisualCue.Indicators>
</local:VisualCue>

但指标没有被绘制。我错过了什么?

4

2 回答 2

1

Have you tried implementing the LogicalChildren method?

protected override IEnumerator LogicalChildren
{
    get { return indicators.GetEnumerator(); }
}

I had all sorts of trouble when I developed my first 'FrameworkElement`.

After extensive research I basically discovered there were a number of methods you have to override in order for it to play nicely with WPF.

于 2012-07-29T19:51:50.307 回答
0

至少您需要在 VisualCue 中覆盖 ArrangeOverride:

protected override Size ArrangeOverride(Size finalSize)
{
    foreach (Indicator indicator in Indicators)
    {
        indicator.Arrange(new Rect(0, 0, 10, 10));
    }

    return finalSize;
}

传递给 Indicator children 的 Rect 中的值取决于您的布局需求。您还应该覆盖 MeasureOverride。

FrameworkElement.ArrangeOverride 方法

FrameworkElement.MeasureOverride 方法

于 2010-03-31T22:56:56.347 回答