tags:

views:

100

answers:

1

Hi,

How do I get the width available for the children of a scroll viewer in XAML? Thanks.

A: 

There's no direct way of doing this that I know of, since WPF automatically passes the available space in to the child controls' Measure() function so that they size to fit the available space.

Note that, by default, it passes in infinity for the vertical direction, since content can scroll forever vertically. You can change the visibility of the scroll bars in both the vertical and horizontal direction to affect whether infinity is passed vertically, horizontally, or both.

The best way of figuring out how wide the child controls actually have to layout in pure XAML would be to create an empty control - for instance, an empty grid - and then bind to its ActualWidth property:

<ScrollViewer>
    <StackPanel>
        <Grid x:Name="MeasureGrid"/>
        <TextBox Text="{Binding ElementName=MeasureGrid, Path=ActualWidth}"/>
    </StackPanel>
</ScrollViewer>

Aside from displaying the width that is actually available to controls, I don't see any other use for this information in XAML, though - all of the other scenarios I can think of can use this information implicitly. Can you give us more information on what you are trying to accomplish?

Nicholas Armstrong
The problem is that a TabItem does not take all the available space of TabControl (unless I am missing something). So I have been expanding my elements to the width of the tab control, I need to put a scrollviewer now but I can't figure out the width to give my elements.
grizzley
The contents of a TabItem should fill the available space by default. Are you unintentionally setting the Horizontal/VerticalAlignment properties?
YotaXP
Perhaps? Here is a simple xaml where the button does not fill the TabItem space. <DockPanel> <TabControl> <TabItem Header="Test"> <Button>Test</Button> </TabItem> </TabControl> </DockPanel>
grizzley
That DockPanel snippet works fine in a blank project. Probably what is happening is that you've got that DockPanel inside something that is allowing it to shrink to the size of its contents - as would happen if Horizontal/VerticalAlignment were set. Try replacing that whole control with a Rectangle, and then playing around with the parent panels and/or the Horizontal/VerticalAlignment properties until the rectangle fills the available space. Or edit your question and provide more code so we can have a better idea of what other controls are involved.
Nicholas Armstrong