Garbage Collector
Garbage Collector

Reputation: 106

Multiple canvas layers on custom panel

Continuation of this question. I can create custom panel or even canvas and add multiple DrawingVisual to it. Now, I'd like to add multiple Canvas controls to this custom panel. Unfortunately, Canvas is not being rendered.

Why Canvas is different from DrawingVisual and how to create custom panel that could show several Canvas and several DrawingVisual at the same time?

public class BoardControl : Panel
{
  protected IList<Visual> _visuals = new List<Visual>();
  protected IDictionary<dynamic, int> _maps = new Dictionary<dynamic, int>();
  protected override int VisualChildrenCount => _visuals.Count;
  protected override Visual GetVisualChild(int index) => _visuals.ElementAtOrDefault(index);
  //protected override IEnumerator LogicalChildren => _visuals.GetEnumerator();
  //public new UIElementCollection Children => new UIElementCollection(this, this);
  //public new UIElementCollection InternalChildren => new UIElementCollection(this, this);

  public virtual Visual this[dynamic name]
  {
    get => _maps.TryGetValue(name, out int index) ? _visuals.ElementAtOrDefault(index) : default;

    set
    {
      if (value == null)
      {
        _maps.TryGetValue(name, out int index);
        var visual = GetVisualChild(index);

        _maps.Remove(name);
        _visuals.RemoveAt(index);

        base.RemoveVisualChild(visual);
      }
      else
      {
        _maps[name] = _visuals.Count;
        _visuals.Add(value);

        //if (value is Canvas)
        //{
        //  Children.Add(value as UIElement);
        //  return;
        //}

        base.AddVisualChild(value);
      }
    }
  }
}

Upvotes: 0

Views: 232

Answers (1)

RolandJS
RolandJS

Reputation: 1055

A Canvas is a Panel, not a Control. A Canvas has no default visible elements on its own. Instead it is showing UIElements (Controls, Panels ...) that you add to its Children property. But you can make a Canvas visible if you set the Background, Width and Height properties.

A DrawingVisual can only contain drawing elements. See DrawingContext. It needs also some kind of host to show the drawings.

See this sample where they add DrawingVisuals to a host and at the end adding the host to a Canvas.

https://github.com/Microsoft/WPF-Samples/tree/master/Visual%20Layer/DrawingVisual

Upvotes: 1

Related Questions