我正在尝试使用这个简单的代码访问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>
我做错了什么?
答案 0 :(得分:3)
试试这个
Grid grid = this.LayoutRoot.Children[1] as Grid;
错误即将发生,因为this.LayoutRoot.Children[1]
返回UIElement
的对象,它是许多WPF控件的基类,例如Grid
您需要做的是使用UIElement
Grid
转换为as