我正在为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).
答案 0 :(得分:1)
您错过了构造函数中的InitializeComponent()
调用。
只要您不调用此方法,所有XAML定义的元素都为null。
因此,访问MyWebView
会引发NullReferenceException
。
如需更多信息,请查看以下问题:What does InitializeComponent() do, and how does it work in WPF?