等待按钮按下
本文关键字:按钮 等待 | 更新日期: 2023-09-27 17:49:18
我有一个 WPF 应用程序,它需要在 XML 文件中向用户显示对象的名称,等待他们读取它,然后允许他们按"继续"按钮并查看下一个按钮。
我已经简化了下面的代码,但需要一种方法来等待按钮按下。
private void Waitforpress()
{
XDocument puppies = XDocument.Load(@"C:'puppies.xml");
foreach (var item in puppies.Descendants("Row")
{
PuppyName = item.Element("puppyName").Value;
// Call Print PuppyName function
// WAIT HERE FOR BUTTON PRESS BEFORE GOING TO NEXT PUPPY NAME
}
}
您不应该像那样真正将文件加载到按钮内,我建议您创建一个将文件读取到队列中的过程,当用户按下按钮时,您读取下一个排队的项目并将其显示给用户,例如:
Queue<XElement> puppiesQueue = new Queue<XElement>();
void LoadPuppies()
{
XDocument puppies = XDocument.Load(@"C:'puppies.xml");
foreach (XElement puppie in puppies.Descendants("Row"))
puppiesQueue.Enqueue(puppie);
}
void Button_Click()
{
//Each time you click the button, it will return you the next puppie in the queue.
PuppyName = puppiesQueue.Dequeue().Element("puppyName").Value;
}
可以使用
以下方法创建单击按钮时将完成的Task
:
public static Task WhenClicked(this Button button)
{
var tcs = new TaskCompletionSource<bool>();
RoutedEventHandler handler = null;
handler = (s, e) =>
{
tcs.TrySetResult(true);
button.Click -= handler;
};
button.Click += handler;
return tcs.Task;
}
然后,您可以await
该任务,以便在单击按钮后继续执行您的方法:
private async Task Waitforpress()
{
XDocument puppies = XDocument.Load(@"C:'puppies.xml");
foreach (var item in puppies.Descendants("Row")
{
PuppyName = item.Element("puppyName").Value;
// Call Print PuppyName function
await button.WhenClicked();
}
}
请注意,您可能希望异步而不是同步地执行文件 IO,以免阻塞 UI 线程。