MattPil29
MattPil29

Reputation: 305

XAML: How to restrict a datagrid to its parents width

I have a [silverlight] WizardContainer control that hosts a number of wizard pages. The wizard fits nicely on its host form. If the page has narrow content it doesn't expand to fill the container. So I set HorizontalContentAlignment to Stretch. This works.

However if the wizard page contains a datagrid with lots of columns it stretches the page instead of autoscrolling itself - as its width is not fixed. If the following XAML is on a usercontrol with a width of 350 I want the grid to be 350 and have its own scrollbars. If the WizardContainer is made smaller than the page minwidth then the MainScroller should come into play.

<Grid x:Name="LayoutRoot" >
   <ScrollViewer x:Name="MainScroller"
                 VerticalScrollBarVisibility="Auto"
                 HorizontalScrollBarVisibility="Auto" >
      <ContentControl Margin="4"  x:Name="WizardContainer"
                      HorizontalContentAlignment="Stretch">
         <Grid Background="Red" x:Name="WizardPage" MinWidth="300">
            <sdk:DataGrid HorizontalAlignment="Left" Height="120" >
               <sdk:DataGrid.Columns>
                  <sdk:DataGridTextColumn  Width="150"/>
                  <sdk:DataGridTextColumn  Width="150"/>
                  <sdk:DataGridTextColumn  Width="150"/>
               </sdk:DataGrid.Columns>
            </sdk:DataGrid>
         </Grid>         
      </ContentControl>
   </ScrollViewer>
</Grid>

Note if I fix the width of the datagrid everything in this XAML works. But I want the grid to expand as the user resizes the form containing the wizardcontainer.

Upvotes: 0

Views: 1570

Answers (1)

XAMeLi
XAMeLi

Reputation: 6289

You have the DataGrid wrapped in ScrollViewer. This, effectively, tells the DataGrid that it has infinite available width. Since the DataGrid is not constrained, it'll take as much width as it's columns desire.

You can set HorizontalScrollBarVisibility="Disabled"if that fits your design (i.e. you need only vertical scrolling from your ScrollViewer). This will disable scrolling horizontally and will constrain the DataGrid on the horizontal axis.

DataGrid has a ScrollViewer in it's ControlTemplate. As a broad general rule: try avoiding a ScrollViewer-in-a-ScrollViewer situations. It's (almost) always a headache to debug and eventually you'll have to set something as a fixed size (or calculate the size on the fly).

Upvotes: 2

Related Questions