WP8在运行时获得Grid(内容面板)高度

时间:2014-01-29 13:31:35

标签: c# wpf visual-studio-2012 windows-8 windows-phone-8

我有一个基本问题。我有这样的MainPage.xaml代码,

<!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

        <!--TitlePanel contains the name of the application and page title-->
        <StackPanel Grid.Row="0" Margin="12,17,0,28">

            <TextBlock Text="{Binding Path=LocalizedResources.ApplicationTitle, Source={StaticResource LocalizedStrings}}" 
                       Margin="9,-7,0,0"  Style="{StaticResource PhoneTextTitle1Style}" Foreground="Black" />
        </StackPanel>

        <!--ContentPanel - place additional content here-->
        <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0" >

        </Grid>
    </Grid>

在我的MainPage.xaml.cs文件中,

public MainPage()
        {
            InitializeComponent();

            MessageBox.Show(ContentPanel.Height.ToString());
        }

我的消息框返回NaN值,但我希望获得特定值而不是无限值。

感谢。

2 个答案:

答案 0 :(得分:2)

您应该在Loaded事件中检查内容面板的实际高度。在构造函数中它将是NaN,因为实际值尚未确定......

答案 1 :(得分:0)

根据建议,

public MainPage()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(DisplayMessage);
        }

void DisplayMessage(object sender, RoutedEventArgs e)
        {
            MessageBox.Show(ContentPanel.ActualHeight.ToString());
        }

这会返回我的内容面板的高度。

感谢。