Independent width in a WPF Grid

可紊 提交于 2020-01-22 00:38:11

问题


I have a grid with 2 rows and 2 columns in WPF. I would like that the column widths are independent for each row. I tried "auto", but no success. Here is a picture in order to explain:

How can I accomplish this using grid?


回答1:


If you must use a grid layout, then you have a couple of options:

Option 1: Make each row a single column and then nest a grid in each row you would like independent columns:

XAML

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>

    <TextBlock Text="AAAAAAAAAAAAAAAAAAAA" />

    <Grid Grid.Row="1">
      <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
      </Grid.ColumnDefinitions>

      <TextBlock Text="BBBBBBB"">
      <TextBlock Grid.Column="1" Text="CCCCCCC" />
    </Grid>
</Grid>

Option 2: Make use of ColumnSpan in the rows:

XAML

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition />
    <RowDefinition />
  </Grid.RowDefinitions>

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

      <TextBlock Grid.ColumnSpan="2" Text="AAAAAAAAAAAAAAAAAAAA" />
      <TextBlock Grid.Row="1" Text="BBBBBBB"">
      <TextBlock Grid.Row="1" Grid.Column="1" Text="CCCCCCC" />
    </Grid>
</Grid>

*These were typed without an editor and may need a bit of tweaking.




回答2:


Two grids?

<StackPanel Width="277">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="AAAAAAAAAAAAAAAAAAAA" Grid.Row="0" Grid.Column="0"/>            
    </Grid>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Text="BBBBBBB" Grid.Row="0" Grid.Column="0"/>
        <TextBlock Text="CCCCCCC" Grid.Row="0" Grid.Column="1"/>
    </Grid>
</StackPanel>


来源:https://stackoverflow.com/questions/14185191/independent-width-in-a-wpf-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!