簡體   English   中英

無法訪問LayoutRoot:無法將類型'System.Windows.UIElement'隱式轉換為'System.Windows.Controls.Grid'

[英]Can't access LayoutRoot: Cannot implicitly convert type 'System.Windows.UIElement' to 'System.Windows.Controls.Grid'

我正在嘗試使用這個簡單的代碼訪問LayoutRoot子項

using System.Windows.Controls;
using Microsoft.Phone.Controls;

namespace PhoneApp2
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Grid grid = this.LayoutRoot.Children[1];
        }

    }
}

但得到這個錯誤:

無法將類型'System.Windows.UIElement'隱式轉換為'System.Windows.Controls.Grid'。 存在顯式轉換(您是否錯過了演員?)

XAML代碼

<phone:PhoneApplicationPage x:Class="PhoneApp2.MainPage"
                            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                            xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
                            xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
                            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
                            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
                            mc:Ignorable="d"
                            FontFamily="{StaticResource PhoneFontFamilyNormal}"
                            FontSize="{StaticResource PhoneFontSizeNormal}"
                            Foreground="{StaticResource PhoneForegroundBrush}"
                            SupportedOrientations="Portrait"
                            Orientation="Portrait"
                            shell:SystemTray.IsVisible="True">

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

    <StackPanel x:Name="TitlePanel"
                Grid.Row="0"
                Margin="12,17,0,28">
      <TextBlock Text="MY APPLICATION"
                 Style="{StaticResource PhoneTextNormalStyle}"
                 Margin="12,0" />
      <TextBlock Text="page name"
                 Margin="9,-7,0,0"
                 Style="{StaticResource PhoneTextTitle1Style}" />
    </StackPanel>

    <Grid x:Name="ContentPanel"
          Grid.Row="1"
          Margin="12,0,12,0">

    </Grid>
  </Grid>
</phone:PhoneApplicationPage>

我究竟做錯了什么?

嘗試這個

Grid grid = this.LayoutRoot.Children[1] as Grid;

錯誤即將到來,因為this.LayoutRoot.Children[1]返回UIElement對象, UIElement是許多WPF控件的基類,例如Grid

您需要做的是使用as顯式將UIElement轉換為Grid

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM