2012-08-04 70 views
-1

在更改ColumnSpanRowSpan後,我需要Grid佈局中元素的大小。 ActualWidthActualHeight屬性不反映呈現的大小。更改RowSpan和ColumnSpan後渲染元素的大小

<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

+1

您是否在設置新的跨度後嘗試過'grid.UpdateLayout()'? – LPL 2012-08-04 12:40:11

+0

這樣做,謝謝! – Richard 2012-08-04 12:43:00

回答

1

ActualWidthActualHeight,會得到正確的結果,當電網的佈局更新。因此,您必須在網格或其他父元素的LayoutUpdated事件中獲取這兩個屬性。

1

致電Grid.UpdateLayout MethodActualWidthActualHeight將反映新值。

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