通过将Width
设置为Auto
,可以使三列具有相同的宽度。
<Grid x:Name="myGrid">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0">One</Label>
<Label Grid.Row="0" Grid.Column="1" x:Name="label1">Two</Label>
<Label Grid.Row="0" Grid.Column="2">Three</Label>
</Grid>
我想实现的是,如果中间列折叠或隐藏,则其他两个占据剩余空间并获得相等的宽度。
如果由于Width =“ *”而仅将“可见性”设置为“折叠”或“隐藏”,则其他两列的宽度保持不变。
<Label Grid.Row="0" Grid.Column="1" Visibility="Collapsed">Two</Label>
我通过编程将第二列宽度设置为auto来实现了所需的功能,但是我正在寻找其他解决方案(最好是xaml方法之一)。
private void Button_Click(object sender, RoutedEventArgs e)
{
this.myGrid.ColumnDefinitions[1].Width = GridLength.Auto;
this.label1.Visibility = Visibility.Collapsed;
}
答案 0 :(得分:0)
我按照Rob的建议添加了Xaml绑定,如下所示:
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="{Binding MiddleColumnWidth}" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0">One</Label>
<Label Grid.Row="0" Grid.Column="1" Visibility="{Binding IsSecondLabelVisible}">Two</Label>
<Label Grid.Row="0" Grid.Column="2">Three</Label>
xaml后面的代码:
private bool ShowOnlyTwoColumns;
private GridLength MiddleColumnWidth
{
get
{
if (ShowOnlyTwoColumns)
return GridLength.Auto; // Auto collapses the grid column when label is collapsed
return new GridLength(1, GridUnitType.Star);
}
}
private Visibility IsSecondLabelVisible
{
get { return this.ShowOnlyTwoColumns ? Visibility.Collapsed : Visibility.Visible; }
}
答案 1 :(得分:0)