0
点赞
收藏
分享

微信扫一扫

一键清除JavaScript代码中的注释:使用正则表达式实现

秀儿2020 2024-03-12 阅读 7
wpfc#

可能不是最好的办法,但是用起来效果也还是可以的。

原理:通过IsEnabled属性来控制按钮状态。btnConfirm.IsEnabled  / this.IsEndbled 这两种方式是等价的。

案例比较简单,如果后期做开发的话代码量变大,只在结尾添加 this.IsEndbled = true ,逻辑上是有缺陷的。如果txtName为空是不是又要给IsEndbled = True 这样重新赋值。 如果是多个if条件呢这样的话会很繁琐。

所以我就用上了异常捕获

使用 try{    要执行的代码    }catch(Exception ex){    异常    }finally{    最后执行的代码    }

finally

当一个异常抛出时,它会改变程序的执行流程。因此不能保证一个语句结束后,它后面的语句一定会执行,在 C# 中这个问题可以用 finally 解决。

为了确保一个语句总是能执行(不管是否抛出异常),需要将该语句放到一个 finally 块中,finally 要么紧接在 try 块之后,要么紧接在 try 块之后的最后一个 catch 处理程序之后。只要程序进入与一个 finally 块关联的 try 块,则 finally 块始终都会运行 -- 即使发生了一个异常。

Xaml代码:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel>
            <TextBox Name="txtName" Height="30" />
            <ProgressBar Name="progressBar1" Maximum="100" Height="42"  />
            <Label Name="label1"></Label>
            <Button Name="btnConfirm" Click="Button_Click_1" Height="30" Content="添加" />
        </StackPanel>
    </Grid>
</Window>

C#代码:

namespace WpfApplication1
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            this.IsEnabled = false;

            try
            {
                if (!string.IsNullOrEmpty(txtName.Text))
                {
                    MessageBox.Show("用户名称不能为空!");
                    //this.IsEnabled = true;
                    return;
                }

                for (int i = 0; i <= 100; i++)
                {
                    progressBar1.Value = i;
                    System.Windows.Forms.Application.DoEvents();
                    Thread.Sleep(10);
                    label1.Content = "数据正在加载中(" + i + ")";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message,"错误",MessageBoxButton.OK,MessageBoxImage.Error);
            }
            finally
            {
                this.IsEnabled = true;
            }
        }
    }
}
举报

相关推荐

0 条评论