I am using the MVVM Toolkit to build my WP7 apps and I am trying to get a MessageBox to display an error if the WCF service fails.
Here is the code I have in my ServiceHelper layer:
public void GetRandomBibleVerseById(Action<Bible, Exception> callback)
{
var client = new StoneFalconClient();
client.GetRandomBibleVerseByIdCompleted += (s, e) =>
{
var userCallback = e.UserState as Action<Bible, Exception>;
if (userCallback == null)
{
return;
}
if (e.Error != null)
{
userCallback(null, e.Error);
return;
}
userCallback(e.Result, null);
};
client.GetRandomBibleVerseByIdAsync(callback);
}
I tried placing a try/catch around the service call by doing something like this but I don't get any message box to show up with the error. Here is my MainViewModel:
public MainViewModel()
{
if (IsInDesignMode)
{
BibleVerse = LoadDebugVerse();
}
else
{
try
{
ServiceHelper helper = new Serv开发者_开发百科iceHelper();
helper.GetRandomBibleVerseById((bibleVerse, error) =>
{
Bible displayVerse = LoadDisplayVerse(bibleVerse);
BibleVerse = displayVerse;
TestamentBookChapterVerse = displayVerse.Testament + ": " + displayVerse.Book + " " + displayVerse.Chapter + ":" + displayVerse.Verse; ;
});
}
catch (Exception ex)
{
ErrorMessage = new RelayCommand<String>(m => MessageBox.Show("Error: Click refresh to try again"));
}
}
}
I am binding the xaml in the xaml page to the viewModel. I suspect that I shouldn't be using the try/caatch but instead inspecting e.Error but I have no idea how to do that.
Any help would be appreciated, I have been searching forever for an answer with no luck.
RJ,
Your client object (of type StoneFalconClient) should have an AsyncCompleted event that you can register a handler for. In your OnAsyncCompleted handler, there should be an Error field in the EventArgs parameter.
Good luck
Jim McCurdy
精彩评论