views:

134

answers:

1

Hey guys,

I'm having a problem where I have elements such as Listboxes and Rich Text boxes that I want to set to size automatically in xaml according to the size of the window, but I only want it to resize to the size of the window and then put scrollbars if the content is any bigger than that.

Unfortunately, the only way I can get scroll bars to work is if I set a specific height of the listbox/rich text box (which does not work because I want it to automatically resize to the height of the grid that it is contained within, which is generally the height of the window (auto).

Any help would be greatly appreciated.

A: 

You do not need to use fixed values for Width and Height - you should rather specify a minimum width/height for your controls using the MinWidth and MinHeight properties. Then try a layout similar to this:

<Window>
    <ScrollViewer HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto">
        <Grid>

            <ListBox MinWidth="500" MinHeight="250"/>

            <!-- any other controls... -->

        </Grid>
    </ScrollViewer>
</Window>

The Grid generally uses all the space it gets if its alignment properties are set to Stretch and if at least one row/column is set to be star-sized. In this case, there are only one row and one column, implicitly created, both star-sized by default.
To make the ScrollViewer work, you need to somehow set a minimum size of your content controls because otherwise the ScrollViewer does not know when to activate the ScrollBars. In the example above, I have done that using the MinHeight and MinWidth properties of the ListBox, but you could also set these properties on the Grid's RowDefinitions and/or ColumnDefinitions.

Now, if you resize the window, so that the Width becomes smaller than 500, you will see that scrollbars will appear. Just check it out.

gehho
Hey, thanks for your response. The problem is that I cannot set a MinWidth or a MinHeight because I want the MinHeight to be relative to the size of the window... ie. always take up say the top half of the window. If it is 1024 x 768 the minheight should be 334, if it is 1440 x 900 it should be 450, etc.
Jay
Sure. You can achieve that by using star-sized grid rows/columns. But when do you want the ScrollBars to appear? If you *always* want the MinHeight to be relative to the size of the Window, then you *never* need ScrollBars, right?! Because then, even if the window is 30x20, your controls would have a height of 10. You need to define some minimum size which your controls must have. If the window gets too small to keep this size, the ScollBars will appear. Am I missing something here?
gehho