用户控件网格中的一行

Wol*_*mer 3 grid xaml user-controls

我有以下网格:

<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>
Run Code Online (Sandbox Code Playgroud)

问题: 有没有办法创建一个包含Label和TextBox的UserControl,并以正确的方式正确对齐第一列?

Phi*_*hil 6

答案是肯定的,这是可能的,但也许你应该使用DataGrid或带有DataTemplate的ItemsControl.

但问题的简单答案是,如果您需要不同网格中的网格列来同步其宽度,则可以使用SharedSizeGroup属性,例如:

<UserControl>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="column1" Width="auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
    </Grid>
</UserControl>
Run Code Online (Sandbox Code Playgroud)

然后在父元素中使用Grid.IsSharedSizeScope ="True"

<StackPanel Grid.IsSharedSizeScope="True">
    <local:UserControl1/>
    <local:UserControl1/>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

这会同步该范围内具有相同SharedSizeGroup的任何列(或行)(您可以拥有多个嵌套范围).