-1

Grid更改布局后,我需要布局中元素的大小ColumnSpanand RowSpan。和属性ActualWidthActualHeight反映渲染大小。

<Window x:Class="SizeTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525" KeyDown="OnKeyDown">
<Grid Name="grid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Label Name="testElement" Content="Test" Background="Red" Grid.Row="0" Grid.Column="0" Grid.RowSpan="1" Grid.ColumnSpan="1" />
</Grid>

private void OnKeyDown(object sender, KeyEventArgs e)
{
    var w1 = testElement.ActualWidth;
    var h1 = testElement.ActualHeight;

    Grid.SetColumnSpan(testElement, 2);
    Grid.SetRowSpan(testElement, 2);

    var w2 = testElement.ActualWidth;
    var h2 = testElement.ActualHeight;

    MessageBox.Show(string.Format("Initial size: {0}x{1}\nNew size: {2}x{3}", w1, h1, w2, h2));
}

输出:初始尺寸:285.5x160 新尺寸:285.5x160

4

2 回答 2

1

ActualWidth并且ActualHeight会在更新网格布局时为您提供正确的结果。LayoutUpdated所以你必须在你的网格或其他父元素的情况下获得这两个属性。

于 2012-08-04T12:45:24.963 回答
1

调用Grid.UpdateLayout 方法 ActualWidthActualHeight会反映新的值。

Grid.SetColumnSpan(testElement, 2);
Grid.SetRowSpan(testElement, 2);
grid.UpdateLayout()
于 2012-08-04T12:47:43.353 回答