Mahapps ProgressRing WPF C#

Mahapps ProgressRing WPF C#

我试图在 cmd 上执行命令时激活进度环,当命令执行时按钮保持按下状态,当进程完成时按钮保持按下状态,但当进程仍在运行时我无法激活进度环 运行,似乎 WaitForExit 对我不起作用。

 private void Button_Click(object sender, RoutedEventArgs e)
    {

        if (ComboBox.Text == "")
        {
            MessageBox.Show("Select a drive");
        }
        else
        {   
            try
            {
                ProgressRing.IsActive=true;
                Process cmd = new Process();
                cmd.StartInfo.FileName = "cmd.exe";
                cmd.StartInfo.RedirectStandardInput = true;
                cmd.StartInfo.RedirectStandardOutput = true;
                cmd.StartInfo.CreateNoWindow = true;
                cmd.StartInfo.UseShellExecute = false;
                cmd.Start();
                cmd.StandardInput.WriteLine("attrib -r -s -h " + ComboBox.Text + "*.* /s /d");
                cmd.StandardInput.Flush();
                cmd.StandardInput.Close();       
                cmd.WaitForExit();
                ProgressRing.IsActive=false;
            }
            catch (Exception i)
            {
                Console.WriteLine("{0} Exception caught.", i);
                MessageBox.Show("Error");
            }
        }
    }

您应该在后台线程上调用阻塞 WaitForExit 方法。 UI 线程不能同时显示您的 ProgressRing 和等待进程完成。试试这个:

private void Button_Click(object sender, RoutedEventArgs e)
{
    if (ComboBox.Text == "")
    {
        MessageBox.Show("Select a drive");
    }
    else
    {
        ProgressRing.IsActive = true;
        string text = ComboBox.Text;
        Task.Factory.StartNew(() =>
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.Start();
            cmd.StandardInput.WriteLine("attrib -r -s -h " + text + "*.* /s /d");
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.WaitForExit();
        }).ContinueWith(task =>
        {
            ProgressRing.IsActive = false;
            if (task.IsFaulted)
            {
                Console.WriteLine("{0} Exception caught.", task.Exception);
                MessageBox.Show("Error");
            }
        }, System.Threading.CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext());
    }
}