通过代码刷新WPF控制 [英] Refresh WPF-Control by code
问题描述
我正试图禁用一个拒绝垃圾邮件按钮的按钮。
I am trying to disable a button for denying a spam click on this button.
我使用了Refresh委托来渲染控件,但该控件显示为已启用。
connect()-Methode在巫婆中花费了大约4秒钟,按钮显示为已启用。
I used a Refresh delegate to Render invoke the control but it appears as enabled. The connect()-Methode is taking about 4 seconds in witch the button is shown as enabled.
问题出在哪里?
public static class ExtensionMethods
{
private static Action EmptyDelegate = delegate() { };
public static void Refresh(this UIElement uiElement)
{
uiElement.Dispatcher.Invoke(DispatcherPriority.Render, EmptyDelegate);
}
}
private void buttonConnect_Click(object sender, RoutedEventArgs e)
{
this.Cursor = Cursors.Wait;
buttonConnect.IsEnabled = false;
buttonConnect.Refresh();
if (buttonConnect.Content.Equals("Connect"))
{
connect();
}
else
{
disconnect();
}
buttonConnect.IsEnabled = true;
buttonConnect.Refresh();
this.Cursor = Cursors.Arrow;
}
推荐答案
在UI线程上,UI没有时间在其间进行更新,您需要在后台线程上运行任务,并在完成后再次更改UI(例如,使用 BackgroundWorker
已具有 RunWorkerCompleted
事件)。
Since all that appears to happen on the UI-Thread the UI has no time to update in-between, you need to run your task on a background thread and change the UI again on completion (e.g. use a BackgroundWorker
which already has a RunWorkerCompleted
event).
例如
button.IsEnabled = false;
var bw = new BackgroundWorker();
bw.DoWork += (s, _) =>
{
//Long-running things.
};
bw.RunWorkerCompleted += (s,_) => button.IsEnabled = true;
bw.RunWorkerAsync();
这篇关于通过代码刷新WPF控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!