WPF浏览器应用程序空引用错误

时间:2014-02-03 02:40:21

标签: .net wpf windows

我有这个代码,但每当我在第22行构建它时,它会给我一个NullReference错误。 我能知道我在哪里犯错吗?

提前致谢。

public partial class Page4 : Page
{

    DispatcherTimer introTime = new DispatcherTimer();

    public Page4()
    {
        InitializeComponent();
        introTime.Interval = TimeSpan.FromSeconds(4);
        introTime.Tick += new EventHandler(introTime_Tick);
        introTime.Start();
    }

    private void ToggleButton_Click(object sender, RoutedEventArgs e)
    {
        this.NavigationService.Navigate(new Uri("Page1.xaml", UriKind.Relative));
    }

    private void introTime_Tick(object sender, EventArgs e)
    {
        if (button1.IsChecked == false)
        {
            this.NavigationService.Navigate(new Uri("Page1.xaml", UriKind.Relative));
        }
    }

}

1 个答案:

答案 0 :(得分:0)

在实例化之前,您似乎正在尝试访问NavigationService。您可以覆盖OnLoaded并执行正文中的Timespan.Tick位。

结果看起来像这样

private void introTime_Tick(object sender, EventArgs e)
{
    if (button1.IsChecked == false)
    {
        this.NavigationService.Navigate(new Uri("Page1.xaml", UriKind.Relative));
    }
}

void OnLoad(object sender, RoutedEventArgs e)
{
    introTime.Interval = TimeSpan.FromSeconds(4);
    introTime.Tick += new EventHandler(introTime_Tick);
    introTime.Start();

}

WPF Navigation Overview