Search code examples
c#wpfxaml

how to have the viewbox keep its size?


In a wpf application, I have a user control with a Grid "ContentGrid" which can get bigger than the user control, then all the parents of ContentGrid are resized too big.

I do not understand why the Viewbox does not do its job and keep everything inside resized so one can see everything, with no resizing of controls outside it.

In particular, this user control "myUC" is placed inside another Grid, Inside a Window; when ContentGrid gets too big, the user control also gets too big, and the most parent grid overflows beyond the limit of the Window.

How to make sure the content of the viewbox won't resize its parents ? Or how to make sure the most paretn Grid won't overflow the Window ?

<UserControl x:Class="myUC">
    <Grid>
        <Viewbox>
            <Grid Name="ContentGrid">

Simplified Window:

<Window>
    <Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="5"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    
    <myUC Grid.Row="0", Grid.RowSpan="1"/>

Solution

  • The way is to bind the viewbox's MaxHeight to user control's ActualHeight, so it never get bigger than the user control:

    <UserControl x:Class="myUC">
        <Grid>
            <Viewbox MaxHeight="{Binding ActualHeight,
             RelativeSource={RelativeSource AncestorType=local:myUC}}">