locked
How to insert Image in my Canvas? RRS feed

  • Question

  • I want to add an Image in MyCanvas:

    public class MyCanvas : Canvas
    {
        private VisualCollection children;
    
        public MyCanvas()
        { this.children = new VisualCollection(this); }
    
    
        public void AddVisual(Visual visual)
        { this.children.Add(visual); }
    
        public void RemoveVisual(Visual visual)
        { this.children.Remove(visual); }
    
        public void ClearVisuals()
        { this.children.Clear(); }
    
    
        protected override int VisualChildrenCount
        {
            get
            { return this.children.Count; }
        }
    
        protected override Visual GetVisualChild(int index)
        { return this.children[index]; }
    }

    I tried:

    my_canvas.Children.Add(my_image);
    // or also
    my_canvas
    .AddVisual(my_image);

    But my_image does not appear. What is the problem and how i have to fix it?

    Thanks.

    Thursday, May 17, 2012 4:38 PM

Answers

  • The image is not rendered because you have overridden GetVisualChild and you return only your own visuals. Any visuals generated by children of the Canvas are simply ignored.

    Since you're working directly with visuals you probably should use a DrawingVisual and an ImageSource instead of an Image. In the DrawingVisual you can simply render the ImageSource with DrawingContext.DrawImage.

    • Marked as answer by doh666 Thursday, May 17, 2012 5:31 PM
    Thursday, May 17, 2012 5:19 PM

All replies

  • The image is not rendered because you have overridden GetVisualChild and you return only your own visuals. Any visuals generated by children of the Canvas are simply ignored.

    Since you're working directly with visuals you probably should use a DrawingVisual and an ImageSource instead of an Image. In the DrawingVisual you can simply render the ImageSource with DrawingContext.DrawImage.

    • Marked as answer by doh666 Thursday, May 17, 2012 5:31 PM
    Thursday, May 17, 2012 5:19 PM
  • There's a bit more over riding to do and invalidatemeasure to force a repaint.

    http://stackoverflow.com/questions/3101868/wpf-element-that-dynamically-creates-encapsulated-children-at-runtime

    Thursday, May 17, 2012 5:26 PM
  • There's a bit more over riding to do and invalidatemeasure to force a repaint.

    http://stackoverflow.com/questions/3101868/wpf-element-that-dynamically-creates-encapsulated-children-at-runtime

    Thanks, but why? Even if i don't override MeasureOverride ad ArrangeOverride it works. could you explain it better please?
    Thursday, May 17, 2012 11:29 PM