Windows Phone学习笔记:在应用程序中处理错误

来源:互联网 发布:淘宝买家要发票怎么办 编辑:程序博客网 时间:2024/04/30 08:14

--------------------------------------------------- 2345王牌技术员联盟、2345王牌技术员联盟、期待与您交流!---------------------------------------------------------

1.    首先,添加一个新的页面到项目工程中。在Solution Explorer视图,右键单击WindowsPhonePuzzle工程节点, 指向Add并选择New Item. 在Add New Item对话框, 从模板列表里选择Windows Phone Portrait Page,把name 设为ErrorPage.xaml然后点击Add

为工程添加一个新的页面

2.    在ErrorPage.xaml文件中,找到名为LayoutRoot的Grid元素,并用下面的蓝色高亮XAML标记代码替换它的子控件。这个XAML定义了一个应用程序标题和页面标题,两个标题都被命名为error。它同样定义了一个TextBlock对象并被指定为x:Name="ErrorText"样式,用来保存任何未来异常的错误文本。

XAML

...

 

<Grid x:Name="LayoutRoot" Background="Transparent">

<Grid.RowDefinitions>

<RowDefinition Height="Auto"/>

<RowDefinition Height="*"/>

</Grid.RowDefinitions>

 

<!--TitlePanel contains the name of the application and pagetitle-->

<StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="24,24,0,12">

<TextBlock x:Name="ApplicationTitle" Text="WINDOWS PHONE PUZZLE" Style="{StaticResource PhoneTextNormalStyle}"/>

<TextBlock x:Name="PageTitle" Text="error" Margin="-3,-8,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>

</StackPanel>

<!--ContentPanel - place additional content here-->

<Grid x:Name="ContentPanel" Grid.Row="1">

<Border BorderBrush="White">

<TextBlock x:Name="ErrorText" Style="{StaticResource PhoneTextSmallStyle}"TextWrapping="Wrap" />

</Border>

</Grid>

</Grid>

 

...



3.     现在,按下F7来打开一个新页面的代码隐藏文件。或者,作为另一种选择,在Solution Explorer视窗上右键单击ErrorPage.xaml然后选择View Code。在文件的最上层插入下面的命名空间。

C#

usingSystem.Windows.Navigation;


4.    然后,把下面代码段中高亮的部分插入到ErrorPag类中。这样做就建立了一个Exception对象,当跳转切换到这个页面的时候会自动挂接到ErrorText.Text。

C#

publicpartialclassErrorPage :PhoneApplicationPage

{

public ErrorPage()

  {

    InitializeComponent();

  }

 

publicstaticException Exception;

 

// Executes when the user navigates to thispage.

protectedoverridevoid OnNavigatedTo(NavigationEventArgse)

  {

    ErrorText.Text =Exception.ToString();

  }

}


5.    当这个页面完成后,无论何时,当一个不能被处理的异常出现,此类事件的句柄会使程序切换到错误的页面,并显示错误的信息。在Solution Explorer视图上,右键单击App.xaml并选择View Code来打开Application类的代码隐藏类。


6.    在App类中,找到Application_UnhandledException事件句柄并用下面的代码(高亮部分)替换句柄方法的程序体。

C#

//Code to execute on Unhandled Exceptions

private void Application_UnhandledException(object sender,ApplicationUnhandledExceptionEventArgs e)

{

if(System.Diagnostics.Debugger.IsAttached)

  {

// An unhandled exception has occurred; break inthe debugger

   System.Diagnostics.Debugger.Break();

  }

 

  e.Handled =true;

ErrorPage.Exception= e.ExceptionObject;

  (RootVisualas Microsoft.Phone.Controls.PhoneApplicationFrame).Source=newUri("/ErrorPage.xaml",UriKind.Relative);

}


--------------------------------------------------- 2345王牌技术员联盟、2345王牌技术员联盟、期待与您交流!---------------------------------------------------------

  



原创粉丝点击