Windows Phone 8 XAML Editor在运行时将变量设置为null

时间:2013-05-02 19:32:36

标签: c# windows-phone-8

我一直在尝试将简单的TextBlock控件添加到我的Windows Phone 8应用程序中,但是一旦我在GUI XAML编辑器中为其指定了一个名称,并尝试在运行时通过C#代码中指定的名称访问该控件获取“NullReferenceExceptions”因为永远不会设置该变量。 我已将问题缩小到PhoneApplicationPage方法“FindName”,即

PhoneApplicationPage.FindName("videoName");

然而,对我的一些控件(在GUI编辑器中创建)这样的调用只返回null。有没有人遇到过这个问题并找到了解决办法?

问候。

InitialiseComponent()方法的内容:

 public void InitializeComponent() {
        if (_contentLoaded) {
            return;
        }
        _contentLoaded = true;
        System.Windows.Application.LoadComponent(this, new System.Uri("/Youtube%20Downloader;component/MainPage.xaml", System.UriKind.Relative));
        this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
        this.TitlePanel = ((System.Windows.Controls.StackPanel)(this.FindName("TitlePanel")));
        this.ContentPanel = ((System.Windows.Controls.Grid)(this.FindName("ContentPanel")));
        this.videoName = ((System.Windows.Controls.TextBlock)(this.FindName("videoName")));
        this.videoImage = ((System.Windows.Controls.Image)(this.FindName("videoImage")));
    }

(videoName和videoImage控件是未添加的控件)

XAML代码(编辑器已生成):

 <phone:PhoneApplicationPage
x:Class="Youtube_Downloader.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">

<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="YOUTUBE DOWNLOADER" Style="{StaticResource PhoneTextNormalStyle}" Margin="12,0"/>
    </StackPanel>

    <!--ContentPanel - place additional content here-->
    <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
        <TextBlock x:Name="videoName" Margin="10,10,0,0" TextWrapping="Wrap" Text="TextBlock" VerticalAlignment="Top" Height="56" FontSize="36" FontStyle="Normal"/>
        <Image x:Name="videoImage" HorizontalAlignment="Center" Height="408" Margin="0,72,0,0" VerticalAlignment="Top" Width="446"/>
    </Grid>
</Grid>

1 个答案:

答案 0 :(得分:0)

我遇到了同样的问题。清洁项目将解决它。