如何向通用Windows应用程序添加异常处理消息?
问题描述:
我正在尝试将相应消息框的异常处理添加到通用Windows应用程序。我只想使用TryParse或Try-Catch,但我无法弄清楚在通用Windows应用程序中与消息框等效的内容。我现在不特别担心它的美学,只要我做的事符合UWP标准,所以我不会陷入前进的坏习惯。如何向通用Windows应用程序添加异常处理消息?
这里是我的C#:
double INCHES = 1;
double FEET = 12;
double YARDS = 36;
double userDist, convertDist, distFrom, distTo;
string unitOfMeasure;
private void convertButton_Click(object sender, RoutedEventArgs e)
{
unitOfMeasure = null;
distFrom = 1;
distTo = 1;
if (inputTextBox.Text != "")
{
userDist = double.Parse(inputTextBox.Text);
if (listBox1.SelectedIndex >= 0 || listBox2.SelectedIndex >= 0)
{
switch (listBox1.SelectedIndex)
{
case 0:
distFrom = INCHES;
unitOfMeasure = " in";
break;
case 1:
distFrom = FEET;
unitOfMeasure = " ft";
break;
case 2:
distFrom = YARDS;
unitOfMeasure = " yd";
break;
}
switch (listBox2.SelectedIndex)
{
case 0:
distTo = INCHES;
unitOfMeasure = " in";
break;
case 1:
distTo = FEET;
unitOfMeasure = " ft";
break;
case 2:
distTo = YARDS;
unitOfMeasure = " yd";
break;
}
convertDist = (userDist * distFrom)/distTo;
outputTextBlock.Text = convertDist.ToString("n2") + unitOfMeasure;
}
else
{
//MessageDialog dialog = new MessageDialog("Please select 'From' and 'To' units.");
}
}
else
{
//MessageDialog dialog = new MessageDialog("Please input a number to convert.");
}
}
private void clearButton_Click(object sender, RoutedEventArgs e)
{
inputTextBox.Text = "";
listBox1.SelectedIndex = -1;
listBox2.SelectedIndex = -1;
outputTextBlock.Text = "";
distFrom = 1;
distTo = 1;
}
private void exitButton_Click(object sender, RoutedEventArgs e)
{
App.Current.Exit();
}
答
我想你注释掉的代码应该工作,如果您还添加 -
等待dialog.ShowAsync();
答
像布赖恩说
MessageDialog dialog = new MessageDialog("Please select 'From' and 'To' units.");
await dialog.ShowAsync();
应该工作。我还补充说,您需要将convertButton_Click标记为异步方法:
private async void convertButton_Click(object sender, RoutedEventArgs e)
太棒了。现在,我忘记了在这个项目中我曾经做过这件事,但当我重新开始时,我得到了一个粗鲁的觉醒:我已经添加了:使用Windows.UI.Popups;到MainPage C#和App C#。我应该在哪里具体说明未来? –
无论你打算使用MessageDialog类,你都必须添加它。 – Seine