본문 바로가기
Programming/Windows Phone

생애 첫 번째 윈도우 폰 7 애플리케이션 만들기 2회

by 강철 벼룩 2011. 2. 24.

 이번 시간에는 처리되지 않은 예외가 발생할 마다 에러 페이지를 표시하도록 애플리케이션을 업데이트 한다. 처리되지 않은 예외를 관리하려면, 우선 해당 에러에 관한 정보를 표시하도록 새로운 페이지를 애플리케이션에 추가한다. 다음 UnhandledException 이벤트에 관한 이벤트 핸들러를 생성한다. 이벤트는 애플리케이션에서 예외가 잡히지 않을 마다 발생한다. 핸들러에서 해당 예외에 관한 정보를 전달해 에러 페이지를 찾게 된다.

1. 먼저 프로젝트에 새로운 페이지를 추가한다. [솔루션 탐색기]에서, WindowsPhonePuzzle 프로젝트 노드를 오른 클릭하고, [Add]|[New Item]을 선택한다. [ Add New Item] 대화상자에서, 템플릿 목록의 [Windows Phone Portrait Page]를 선택하고, 이름을 [ErrorPage.xaml]로 설정한 뒤 [Add]를 클릭한다.

[그림 4] 프로젝트에 새로운 페이지 추가하기

2. ErrorPage.xaml에서 LayoutRoot Grid 요소를 찾아서 아래 XAML 마크업으로 해당 요소의 자식 컨트롤을 대체한다. 이 XAML은 애플리케이션의 제목과 페이지 제목을 정의한다. 또한, 지정된 TextBlock 객체를 x:Name="ErrorText"로 정의해 향후 나타나는 모든 예외들에서 에러 텍스트를 표시한다.

 

...

<Grid x:Name="LayoutRoot" Background="Transparent">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

<!--TitlePanel contains the name of the application and page title-->
    <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. 새로운 페이지의 코드 숨김 파일을 열어, 다음의 네임스페이스 지시문을 파일의 상단에 삽입한다.

using System.Windows.Navigation;

4. ErrorPage  클래스에 다음 코드를 삽입한다. 코드는 Exception 객체를 설정해 ErrorText.text 연결시킨다.

 

public partial class ErrorPage : PhoneApplicationPage
{
  public ErrorPage()
  {
    InitializeComponent();
  }

public static Exception Exception;

// Executes when the user navigates to this page.
  protected override void OnNavigatedTo(NavigationEventArgs e)
  {
    ErrorText.Text = Exception.ToString();
  }
}


5. 일단 페이지가 준비 되면, 이벤트 핸들러를 연결해 에러 페이지를 탐색하고 처리되지 않은 예외가 발생할 때마다 에러 메시지를 표시한다. [솔루션 탐색기]에서, App.xaml 코드 숨김 파일을 표시한다.

6. App 클래스에서 Application_UnhandledException 이벤트 핸들러를 찾아서 메서드의 본문을 다음의 코드로 대체 한다.

 

// 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 in the debugger
    System.Diagnostics.Debugger.Break();
  }

e.Handled = true;
  ErrorPage.Exception = e.ExceptionObject;
  (RootVisual as Microsoft.Phone.Controls.PhoneApplicationFrame).Source =
      new Uri("/ErrorPage.xaml", UriKind.Relative);
}


이제 애플리케이션을 빌드하고 윈도우 에뮬레이터로 배포한 다음, 결과를 확인해보자. 결과를 확인하는 절차는 다음과 같다.

1. 비주얼 스튜디오에서 [CTRL +F5] 눌러 디버깅 없이 애플리케이션을 윈도우 에뮬레이터로 실행한다. 잠깐 기다리면 애플리케이션이 실행하고 메인 페이지를 표시한다.

[그림 5] 에뮬레이터에서 애플리케이션 실행 시작화면

2. [START] 버튼을 클릭한다. 애플리케이션에서 앞서 정의한 처리되지 않은 예외 에러 페이지를 표시한다. 버튼에 대한 핸들러가 아직 정의하지 않은 PuzzlePage.xaml 페이지를 탐색하기 때문에 이런 결과가 나오는 것이다.

[그림 6] 처리되지 않은 예외 에러 페이지