c# - 如何在 WPF 中获取 gui 元素的值?
问题描述
我正在尝试从调度程序获取元素的值。但是,我无法理解如何稍后在代码中传递它。我想将有关已完成操作的进度传递给测试箱。
每当我ProductId.Text
在主线程中使用时,我都会获得价值。
Task.Run(() =>
{
ProductId.Dispatcher.Invoke(() =>
{
string productId = ProductId.Text;});
Console.WriteLine($"Creating game {productId}");
});
我只是想稍后在代码中传递变量 productId。有任何想法吗?
解决方案
从评论来看,似乎有一个长期运行的后台进程需要将更新发布到 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 元素中读取其输入,无论它可能是什么。它接受它需要的输入,图像列表,作为参数。这使得在后台运行更容易,更容易测试和修改。
例如,可以修改代码以显示文件夹浏览器对话框,而不是从文本框中读取。
推荐阅读
- javascript - 映射数组在 React Hooks useState 中进行本地存储时出现错误渲染(一切看起来都颠倒了)* 第一次代码看起来很乱
- coinbase-api - Coinbase API:获取多种资产的现货价格
- python - 在 numpy 数组中查找与所有其他行相比具有最小值的行
- r - 在 R 中获取非营利组织的数据集 Tidy;复杂的枢轴
- awk - 仅当前一行具有另一个特定模式时才删除具有模式的行
- python - 拆分和切片抓取的 python 列表
- reactjs - TypeError:无法读取未定义的属性(读取“加载”)
- c# - C# Web API:迭代数组并追加到 HTML 表
- javascript - 我可以将变量定义为数组中的任何字符串吗?
- c - 程序在第二次循环后不起作用