Giả sử bạn có một số nút (căn chỉnh theo chiều ngang) trong trang và cần ẩn/hiển thị các nút nhất định tùy thuộc vào một số trạng thái.
<Grid HorizontalAlignment="Center" Grid.Column="1" Width="340" VerticalAlignment="Center" Background="Transparent">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" x:Name="colOne"></ColumnDefinition>
<ColumnDefinition Width="0" x:Name="colTwo"></ColumnDefinition>
<ColumnDefinition Width="0" x:Name="colThree"></ColumnDefinition>
<ColumnDefinition Width="0" x:Name="colFour"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Button x:Name="btnOne" Grid.Column="0" Height="50" Width="50" Content="One" Cursor="Hand" />
<Button x:Name="btnTwo" Grid.Column="1" Height="50" Width="50" Content="Two" Cursor="Hand" />
<Button x:Name="btnThree" Grid.Column="2" Height="50" Width="50" Content="Thre" Cursor="Hand" />
<Button x:Name="btnFour" Grid.Column="3" Height="50" Width="50" Content="Four" Cursor="Hand" />
</Grid>
Tại đây, btnOne sẽ hiển thị trong trang khi được thực thi. btnOne cũng sẽ được căn chỉnh ở giữa. Bây giờ nếu chúng ta muốn Ba và Bốn được hiển thị và Một để được ẩn khi nhấp vào Một, chúng ta có thể sử dụng mã này:
private void btnOne_Click(object sender, RoutedEventArgs e)
{
SetGridColWidth(colOne, false);
SetGridColWidth(colThree, true);
SetGridColWidth(colFour, true);
}
private void SetGridColWidth(ColumnDefinition column, bool show)
{
if (show)
column.Width = new GridLength(2, GridUnitType.Star);
else
column.Width = new GridLength(0);
}
Bạn có thể chuyển đổi giữa mức hiển thị của bất kỳ nút nào khi chạy.
Hy vọng điều này sẽ giúp ai đó!
Nguồn
2015-03-06 06:50:55
thể trùng lặp của [Lưới Star-Kích thước trong mã đằng sau] (http://stackoverflow.com/questions/5459595/grid-star-size-in-code-behind) –