前回:Windows Phone Developer Tools 7.1 betaを入れたら実行時エラーが
Claudia x Clockを作成中に遭遇した不具合でしたので、実行時エラーが発生する最小コードを作成して再現してみました。
XAML定義
まずは、MainPage.xamlはこんな感じにしています。
エラーとなるコード
つぎに実行時エラーとなるMainPage.xaml.vbですが、こんな感じです。
Partial Public Class MainPage
Inherits PhoneApplicationPage
Private WithEvents GetPhoto As New Microsoft.Phone.Tasks.PhotoChooserTask
' Constructor
Public Sub New()
InitializeComponent()
End Sub
Private Sub SelectButton_Click(sender As System.Object,
e As System.Windows.RoutedEventArgs)
GetPhoto.ShowCamera = True
GetPhoto.Show()
End Sub
Private Sub GetPhoto_Completed(sender As Object,
e As Microsoft.Phone.Tasks.PhotoResult) Handles GetPhoto.Completed
If e.Error Is Nothing AndAlso e.TaskResult = Microsoft.Phone.Tasks.TaskResult.OK Then
Dim image As New System.Windows.Media.Imaging.BitmapImage
image.SetSource(e.ChosenPhoto)
Me.Background_Image.Source = image
End If
End Sub
End Class
Completedイベントで背景画像を設定しているところで実行時エラーになります(エミュレータのときだけで実機では動く)。
動作するコード
同じ処理をするコードでも実行時エラーがでないコードもかけました。
Partial Public Class MainPage
Inherits PhoneApplicationPage
Private GetPhoto As Microsoft.Phone.Tasks.PhotoChooserTask
' Constructor
Public Sub New()
InitializeComponent()
GetPhoto = New Microsoft.Phone.Tasks.PhotoChooserTask
AddHandler GetPhoto.Completed, AddressOf GetPhoto_Completed
End Sub
Private Sub SelectButton_Click(sender As System.Object,
e As System.Windows.RoutedEventArgs)
GetPhoto.ShowCamera = True
GetPhoto.Show()
End Sub
Private Sub GetPhoto_Completed(sender As Object,
e As Microsoft.Phone.Tasks.PhotoResult)
If e.Error Is Nothing AndAlso e.TaskResult = Microsoft.Phone.Tasks.TaskResult.OK Then
Dim image As New System.Windows.Media.Imaging.BitmapImage
image.SetSource(e.ChosenPhoto)
Me.Background_Image.Source = image
End If
End Sub
End Class
つまり、WithEvents付の変数宣言をせずにAddHandesでイベントプロシージャとして登録して使う分にはエラーがでないのです。
参考までにC#コード
なぜ、このような解決方法にたどり着けたかといえば、エラー報告するならばVBとC#の両方を書いた方がいいかなと思い次のようなC#コードを書いたところ正常に動作したからに他なりません。
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using System.Windows.Media.Imaging;
using Microsoft.Phone.Tasks;
namespace MangoBetaBug01Cs
{
public partial class MainPage : PhoneApplicationPage
{
private Microsoft.Phone.Tasks.PhotoChooserTask GetPhoto;
// Constructor
public MainPage()
{
InitializeComponent();
GetPhoto = new Microsoft.Phone.Tasks.PhotoChooserTask();
GetPhoto.Completed += new EventHandler(GetPhoto_Completed);
}
private void SelectButton_Click(object sender, RoutedEventArgs e)
{
GetPhoto.ShowCamera = true;
GetPhoto.Show();
}
private void GetPhoto_Completed(object sender, PhotoResult e)
{
if (e.Error == null & e.TaskResult == TaskResult.OK)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
this.Background_Image.Source = image;
}
}
}
}
とりあえず解決方法が分かりましたが、ちょっと釈然としないですね。