Auto resizing wpf elements with scroll bars (Rich text box, list box) vb
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开发者_JAVA百科 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.
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 ScrollBar
s. 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 RowDefinition
s and/or ColumnDefinition
s.
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.
精彩评论