如何将异常处理消息添加到通用Windows应用程序中

本文关键字:Windows 应用程序 添加 异常处理 消息 | 更新日期: 2023-09-27 18:27:48

我正在尝试将异常处理和相应的消息框添加到通用Windows应用程序中。我只想使用TryParse或TryCatch,但我不知道在通用的windows应用程序中,什么等效于消息框。我现在并不特别担心它的美学,只要我所做的一切都符合UWP的标准,这样我就不会养成前进的坏习惯。

这是我的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();
    }

如何将异常处理消息添加到通用Windows应用程序中

我认为如果您还添加-,您注释的代码应该可以工作

等待对话框。ShowAsync();

就像Brian说的

    MessageDialog dialog = new MessageDialog("Please select 'From' and 'To' units.");
    await dialog.ShowAsync();

应该起作用。我还想补充一点,您需要将convertButton_Click标记为异步方法:

   private async void convertButton_Click(object sender, RoutedEventArgs e)