Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserControl for a Row in a Grid

I have following Grid:

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

    <!-- GridRow-Definition -->

    <Label Grid.Row="0" Grid.Column="0">FirstRow:</Label>
    <TextBox Grid.Row="0" Grid.Column="1" Text="{Binding Binding_To_First_Row}" />

    <Label Grid.Row="1" Grid.Column="0">SecondRow:</Label>
    <TextBox Grid.Row="1" Grid.Column="1" Text="{Binding Binding_To_Second_Row}" />

    <!-- many more Label-TextBox-Rows -->
</Grid>

Question: Is there a way to Create a UserControl which contains the Label and TextBox and properly aligns the first Column in a proper way?

like image 327
Stelzi79 Avatar asked Jan 20 '26 07:01

Stelzi79


1 Answers

The answer is yes, it is possible, but perhaps you should be using a DataGrid or an ItemsControl with a DataTemplate.

The simple answer to your question though is, if you need grid columns in different grids to synchronize their widths, you use the SharedSizeGroup attribute, e.g:

<UserControl>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="column1" Width="auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
    </Grid>
</UserControl>

Then in a parent element you use Grid.IsSharedSizeScope="True"

<StackPanel Grid.IsSharedSizeScope="True">
    <local:UserControl1/>
    <local:UserControl1/>
</StackPanel>

This synchronizes any columns (or rows) that have the same SharedSizeGroup within that scope (you can have multiple nested scopes).

like image 76
Phil Avatar answered Jan 22 '26 04:01

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!