Question

Hi have a simple grid containing 2 objects, one in each column :

<Grid>
   <Grid.ColumnDefinitions>
      <ColumnDefinition />
      <ColumnDefinition />
   </Grid.ColumnDefinitions>

   <Rectangle Fill="Blue" Grid.Column="0" />
   <Rectangle Fill="Red" Grid.Column="1" />

</Grid>

What I want : When setting "Visibility = Collapsed" of either Red or Blue rectangle the other takes all the remaining room.

Can I do that with a Grid control?

Thanks

Était-ce utile?

La solution

This will be much easy with other panels like StackPanel or DockPanel.

But in case you are interested only in Grid approach, you can use DataTrigger to see if other rectangle is Collapsed then set Grid.ColumnSpan to 2 for visible rectangle.

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Rectangle Fill="Blue" Grid.Column="0" x:Name="blueRectangle">
        <Rectangle.Style>
            <Style TargetType="Rectangle">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Visibility,
                                ElementName=redRectangle}" Value="Collapsed">
                        <Setter Property="Grid.ColumnSpan" Value="2"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>
    </Rectangle>
    <Rectangle Fill="Red" Grid.Column="1" x:Name="redRectangle">
        <Rectangle.Style>
            <Style TargetType="Rectangle">
                <Style.Triggers>
                    <DataTrigger Binding="{Binding Visibility, 
                                 ElementName=blueRectangle}" Value="Collapsed">
                        <Setter Property="Grid.ColumnSpan" Value="2"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Rectangle.Style>
    </Rectangle>
</Grid>

Autres conseils

I know this is a cheap trick, but it does work:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>

    <Rectangle Fill="Red" Grid.Column="0" />
    <Rectangle Fill="Blue" Grid.Column="1" />

    <Rectangle Fill="Blue" Grid.Column="0" />
    <Rectangle Fill="Red" Grid.Column="1" />
</Grid>
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top