首页 > 解决方案 > 如何在 WPF 中获取 gui 元素的值?

问题描述

我正在尝试从调度程序获取元素的值。但是,我无法理解如何稍后在代码中传递它。我想将有关已完成操作的进度传递给测试箱。

每当我ProductId.Text在主线程中使用时,我都会获得价值。

Task.Run(() =>
            {
                ProductId.Dispatcher.Invoke(() =>
                {
                    string productId = ProductId.Text;});
                Console.WriteLine($"Creating game {productId}");
            });

我只是想稍后在代码中传递变量 productId。有任何想法吗?

标签: c#wpfdispatcher

解决方案


从评论来看,似乎有一个长期运行的后台进程需要将更新发布到 UI。

使用Progress类和IProgress接口很容易做到这一点。这在启用异步 API 中的进度和取消中进行了描述。Progress可以在创建它的线程上引发事件或调用Action<T>回调。IProgress.Report方法允许其他线程向Progress 发送消息

从文章的示例中复制,此方法在后台线程中处理图像。每次它想报告进度时,它都会调用progress.Report(message);

async Task<int> UploadPicturesAsync(List<Image> imageList, IProgress<string> progress)
{
        int totalCount = imageList.Count;
        int processCount = await Task.Run<int>(() =>
        {
            foreach (var image in imageList)
            {
                //await the processing and uploading logic here
                int processed = await UploadAndProcessAsync(image);
                if (progress != null)
                {
                    var message=$"{(tempCount * 100 / totalCount)}";
                    progress.Report(message);
                }
                tempCount++;
            }

            return tempCount;
        });
        return processCount;
}

所需要的只是在启动异步方法之前在 UI 线程中创建一个新的 Progress 实例:

void ReportProgress(string message)
{
    //Update the UI to reflect the progress value that is passed back.
    txtProgress.Text=message;
}

private async void Start_Button_Click(object sender, RoutedEventArgs e)
{
    //construct Progress<T>, passing ReportProgress as the Action<T> 
    var progressIndicator = new Progress<int>(ReportProgress);

    //load the image list *before* starting the background worker
    var folder=txtPath.Text;
    var imageList=LoadImages(folder);
   //call async method
    int uploads=await UploadPicturesAsync(imageList, progressIndicator);
}

从 UI 读取

另一个重要的事情是UploadPicturesAsync 不要尝试从 UI 元素中读取其输入,无论它可能是什么。它接受它需要的输入,图像列表,作为参数。这使得在后台运行更容易,更容易测试和修改。

例如,可以修改代码以显示文件夹浏览器对话框,而不是从文本框中读取。


推荐阅读