3

我试图在窗口显示之前计算StackPanel width, height(位于网格的中间单元格)(例如在窗口构造函数中)。如何实现?

<Window x:Class="WpfApplication2.TestWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="TestWindow" Height="300" Width="300">
<Grid Name="grid">
    <Grid.ColumnDefinitions>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
        <ColumnDefinition></ColumnDefinition>
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
        <RowDefinition></RowDefinition>
    </Grid.RowDefinitions>

    <StackPanel Grid.Row="1" Grid.Column="1" Name="stackPanel"></StackPanel>

</Grid>

测量 Window 也为 stackPanel 设置DesiredSize{0;0}

public partial class TestWindow : Window
{
    public TestWindow()
    {
        InitializeComponent();

        this.Measure(new Size(this.Width, this.Height)); // -> this.DesiredSize = {0;0}

        ...

    }
}

编辑1

以下适用于 FixedPage:

fixedPage.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); 
fixedPage.Arrange(new Rect(0, 0, fixedPage.DesiredSize.Width, fixedPage.DesiredSize.Height));

然后我们可以访问stackPanel.ActualWidthstackpanel.ActualHeight

但是对于Window,它不起作用。

4

1 回答 1

2

试试这个Loaded事件:

public TestWindow()
{
    InitializeComponent();
    this.Loaded += new RoutedEventHandler(TestWindow_Loaded);
}

void TestWindow_Loaded(object sender, RoutedEventArgs e)
{
    //this.DesiredSize shouldnt be {0,0} now
}

编辑:由于事实上 aStackPanel已经占用了 maximum Size,即使其中没​​有项目,它的SizeChanged事件也只会在你添加很多项目时被触发,所以你可以使用这样的SizeChanged事件StackPanel

private void spTest_SizeChanged(object sender, SizeChangedEventArgs e)
{
    if (!(e.PreviousSize.Height == 0 && e.PreviousSize.Width == 0)) //will also be fired after loading
    {
        //Create another Page
    }
}

EDIT2:另一种可能的解决方案:

public MainWindow()
{
    InitializeComponent();
    yourStackPanelName.Loaded += new RoutedEventHandler(yourStackPanelName_Loaded);
}

void yourStackPanelName_Loaded(object sender, RoutedEventArgs e)
{
    double height = ((StackPanel)sender).ActualHeight;
    double width = ((StackPanel)sender).ActualWidth;
}
于 2012-12-12T08:43:21.133 回答