c# - 设置 WPF Mahapps 进度对话框

标签 c# wpf winforms progressdialog

我正在尝试使用 Mahapps 将我的 ProgressBar 替换为进度对话框。

所以我开始写这个:

private void btnClick(object sender, RoutedEventArgs e)
{ 
    ConfRelais();
}

public async void ConfRelais()
{
    var controller = await this.ShowProgressAsync("hey", "hoy");
    controller.Maximum = 128;
    while (flag == 0)
    {
        string data = RelayBoard_Port.ReadTo("\r\n");
        if (data == "ok") { controller.SetMessage("Done Process");
                            flag = 1; }
        else { controller.SetProgress(Int32.Parse(data)); }
    }
    await controller.CloseAsync();
}

但是进度对话框仅在结束时显示。由于我仍然是 c# 的初学者,也许我缺少一些设置此类功能的重要要点。

最佳答案

您应该在后台线程上执行循环:

public async void ConfRelais()
{
    var controller = await this.ShowProgressAsync("hey", "hoy");
    controller.Maximum = 128;
    await Task.Run(() =>
    {
        while (flag == 0)
        {
            string data = RelayBoard_Port.ReadTo("\r\n");
            if (data == "ok")
            {
                controller.SetMessage("Done Process");
                flag = 1;
            }
            else { controller.SetProgress(Int32.Parse(data)); }
        }
    });
    await controller.CloseAsync();
}

单个线程无法同时更新 UI 和执行循环。

你也并不真正需要一个标志。当您收到“ok”时,您可以跳出循环:

while (true)
{
    string data = RelayBoard_Port.ReadTo("\r\n");
    if (data == "ok")
    {
        controller.SetMessage("Done Process");
        break;
    }
    else { controller.SetProgress(Int32.Parse(data)); }
}

关于c# - 设置 WPF Mahapps 进度对话框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60377936/

相关文章:

c# - 如何在 Azure 广告 B2C 上使用自定义角色?

c# - datagrid鼠标双击事件wpf

c# - 如何检测任务栏上的右键单击

winforms - Windows 窗体中 WebBrowser 控件的浏览器版本是什么

c# - 如何使用 C# 针对 Azure AD 验证用户密码

C# 'is' 运算符性能

c# - 跟踪多步骤任务的进度

c# - 从 View 到 ViewModel 的 WPF 事件绑定(bind)?

wpf - 使用 "Attached Property"是输入捕获的好习惯吗?

c# - 如何避免 Winforms 中 ToolStrip 左侧出现 3 个像素间隙?