Search code examples
wpfimagecanvasattachedbehaviors

How to position images with stretch = Uniform when children of a canvas from a behavior?


I have a behavior which adds Images as children of a canvas:

 private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var behavior = d as ImageCanvasBehavior;
            if (behavior == null)
                return;

            // The AssoicatedObjec is a Canvas.
            Canvas canvas = behavior.AssociatedObject as Canvas;
            if (canvas == null)
                return;

            canvas.Children.Clear();

            CroppedBitmap b = (CroppedBitmap)e.NewValue;          

            Image img = new Image();
            img.Source = b;
            img.Width = canvas.ActualWidth;
            img.Stretch = Stretch.Uniform;

            canvas.Children.Add(img);
        }

The img is added about midway of the horizontal and vertical of the canvas. How can they be positioned to the top-left of the canvas?

TIA

Edit#1 First attempt at a visual tree: enter image description here

Edit#2 I believe this to be wrong...Only the image should be showing, not all the black space above and below the image and the image should not be cut off.

enter image description here


Solution

  • Use the attached property:

            Image img = new Image();
            img.Source = b;
            img.Width = canvas.ActualWidth;
            img.Stretch = Stretch.Uniform;
            Canvas.SetTop(img, 0);
            Canvas.SetLeft(img, 0);