MyDaftQuestions
MyDaftQuestions

Reputation: 4691

How to resize UserControl

I have a UserControl in my WPF application. The UserControl has a listbox and could be any size, and underneath are some buttons.

When I place my UserControl in one of my Views, I would like it resize vertically as the parent resizes. BUT, I'd like the ListBox to decrease in heigh, not the entire control. This would mean on smaller screens, the buttons remain on screen but they don't see much content in the ListBox. I can use a MinHeight to ensure the buttons and at least 1 item in the listbox is visible!

I found similar question such as WPF user control does not resize with main window but my code doesn't have any height or width

My UserControl

<Grid>
    <StackPanel>
    <ListBox ItemsSource="{Binding MessageList" ></ListBox>
        <WrapPanel HorizontalAlignment="Center">
        <Button Content="Expand" HorizontalAlignment="Left" Margin="0,0,40,0"/>
        </WrapPanel>
    </StackPanel>
</Grid>

And the View

<Grid>
    <StackPanel>
        <uc:RecentList MessageList="{Binding Messages}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
    </StackPanel>
</Grid>

It doesn't matter how I resize my View, the UserControl appears to stay at the exact same size.

I tried the ViewBoxbut this was scaling everything!

I also tried (in the UserControl)

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <ListBox ItemsSource="{Binding MessageList, RelativeSource={RelativeSource AncestorType=UserControl}}" Grid.Row="0"></ListBox>
        <WrapPanel Grid.Row="1" HorizontalAlignment="Center">
            <Button Content="Expand" HorizontalAlignment="Left" Margin="0,0,40,0"/>                
        </WrapPanel>
</Grid>

But no difference.

Upvotes: 0

Views: 589

Answers (1)

Clemens
Clemens

Reputation: 128013

StackPanel does not stretch its child elements in the direction of its Orientation.

So remove all StackPanels and define two rows in the Grid in the UserControl:

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>

    <ListBox Grid.Row="0" ItemsSource="{Binding MessageList ...}"/>

    <WrapPanel Grid.Row="1" HorizontalAlignment="Center">
        <Button Content="Expand" HorizontalAlignment="Left" Margin="0,0,40,0"/>
    </WrapPanel>
</Grid>

In main view:

<Grid>
    <uc:RecentList ... />
</Grid>

Take a look at the Panels Overview article on MSDN.

Upvotes: 2

Related Questions