【问题标题】:C# - Windows Phone - WebView.Navigate null referenceC# - Windows Phone - WebView.Navigate 空引用
【发布时间】:2015-12-21 06:47:48
【问题描述】:

我正在为 Windows Phone 开发 UWP 应用程序,但我什至无法启动,因为 WebView 元素出现奇怪错误。我还引用了Windows Mobile Extensions for the UWP

这是一个代码:

XAML
<Page
    x:Class="App9.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:App9"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid>
        <WebView x:Name="MyWebView" />
    </Grid>
</Page>

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using Windows.Web.Http;

namespace App9
{
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);

            Uri authorize = new Uri("http://sub.mydomain.com", UriKind.Absolute);

            try
            {
                MyWebView.Navigate(authorize);
            }
            catch(Exception ex)
            {
                System.Diagnostics.Debug.Write(ex.ToString());
            }
        }
    }
}

这是我得到的一个例外:

Exception thrown: 'System.NullReferenceException' in App9.exe
System.NullReferenceException: Object reference not set to an instance of an object.
   at App9.MainPage.<OnNavigatedTo>d__1.MoveNext()The program '[2912] BandTest.exe' has exited with code 0 (0x0).

【问题讨论】:

    标签: c# webview windows-phone uwp


    【解决方案1】:

    您的构造函数中缺少InitializeComponent() 调用。 只要您不调用此方法,所有 XAML 定义的元素都是 null。 因此,访问MyWebView 会抛出NullReferenceException

    欲了解更多信息,请查看以下问题:What does InitializeComponent() do, and how does it work in WPF?

    【讨论】:

    • 这就是我所缺少的。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    相关资源
    最近更新 更多