Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem with ContentControl resizing

I've been hitting my head against a wall with this one for a while now.

I've got a custom control that derives from ContentControl - it's working perfectly EXCEPT that it won't resize to fit its parent, either declaratively OR programatically.

The custom control is parented within (ultimately) a content presenter, and that's correctly sized, but my control just will NOT size itself out to fit.

  (sample.MyControl) - 400x267
-  (System.Windows.Controls.ContentPresenter) - 979x569

Even when I explicitly set the width and height (at the right moment), the size doesn't "stick"

        Debug.WriteLine(string.Format("MyControl {0}: Size is {1}x{2} ({3}/{4})",
            GetHashCode(), this.ActualWidth, this.ActualHeight,
            this.HorizontalAlignment, this.VerticalAlignment));

        Debug.WriteLine(string.Format("Parent is {0}x{1} ({2}/{3})",
                                      parent.ActualWidth, parent.ActualHeight, 
                                      parent.HorizontalAlignment, parent.VerticalAlignment));

        this.Width = parent.ActualWidth;
        this.Height = parent.ActualHeight;

        Debug.WriteLine(string.Format("MyControl {0}: New size is {1}x{2}",
            GetHashCode(), this.ActualWidth, this.ActualHeight));

The above code gives:

MyControl 36022757: Size is 400x267 (Stretch/Stretch)
Parent is 979x569 (Stretch/Stretch)
MyControl 36022757: New size is 400x267

Why! Oh Gods Why!

Anyone got any ideas?

like image 827
Rammesses Avatar asked Dec 03 '22 15:12

Rammesses


1 Answers

You need just to add HorizontalContentAlignment="Stretch" and VerticalContentAlignment="Stretch" to your control:

<ContentControl HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch">
    ...
</ContentControl>

In such cases Silverlight Spy tool can be helpful for debugging layout in runtime.

Try to run your application in this tool and you will be able to view all xaml elements and even change some properties in runtime.

like image 95
Alexander K. Avatar answered Dec 27 '22 00:12

Alexander K.