0

I am building a simple CAD program. For speed purposes I am using DrawingVisuals. In order to facilitate this I created a custom Canvas class that inherits from Canvas. I override VisualChildrenCount and GetVisualChild inside this class

    protected List<Visual> visuals = new List<Visual>();
    protected override int VisualChildrenCount
    {
        get { return visuals.Count; }
    }
    protected override Visual GetVisualChild(int index)
    {
        if (index < 0 || index >= visuals.Count)
            throw new ArgumentOutOfRangeException("index");
        return visuals[index];
    }

I am displaying this canvas inside a ScrollViewer control in my app. My problem is that I would also like to be able to add different FrameworkElements to my canvas as well. I've tried doing something like this in my canvas code:

TextBox tb = new TextBox();
this.Children.Add(tb);    
tb.Width = 100;
tb.Height = 100;
Canvas.SetLeft(tb, 50);
Canvas.SetTop(tb, 20);

but nothing shows up on my canvas. If I comment out the Visual overrides, it works fine and adds the Textbox to my canvas. Am I missing something here? Do I need to override other methods in order to get FrameworkElements to work? Should I not add the FrameworkElement to the Children collection and add it to visuals instead?

thanks

David
  • 181
  • 13
  • 1
    Do not use a derived Canvas. Instead, create a "visual host" as explained [here](https://learn.microsoft.com/en-us/dotnet/framework/wpf/graphics-multimedia/using-drawingvisual-objects) and add that to a Canvas. Alternatively, override the Canvas's OnRender method and draw into the passed DrawingContext. – Clemens Jul 13 '20 at 07:39
  • Should I draw all my visuals into one host, or is it one host per visual? – David Jul 13 '20 at 08:33
  • That's up to you. If it's a single complex drawing below all other elements, overriding OnRender should work well. – Clemens Jul 13 '20 at 08:47

0 Answers0