[英]how to increase the value of a progress bar by clicking a button in WPF?
in WPF, i have a Progress bar, and i want to increase the value of that progress bar after clicking a button.在 WPF 中,我有一个进度条,我想在单击按钮后增加该进度条的值。 i tried creating an instance of the timer class when the button is clicked and increment the value of the progress bar inside the timer's timer callback method , but it doesn't work and throws the invalid operation exception .
我尝试在单击按钮时创建计时器类的实例,并在计时器的计时器回调方法中增加进度条的值,但它不起作用并引发无效操作异常。 here's the code i have:
这是我的代码:
public MainWindow()
{
InitializeComponent();
}
private void btnProgress_Click(object sender, RoutedEventArgs e)
{
Timer timer = new Timer(TimerCallback, null, 0, 100);
}
private void TimerCallback(Object o)
{
progressBar.Value += 2;
}
You're trying to update a UI control from a non-UI thread.您正在尝试从非 UI 线程更新 UI 控件。 Easy to fix by changing the TimerCallback method as shown below.
通过更改 TimerCallback 方法很容易修复,如下所示。
private void TimerCallback(Object o)
{
progressBar.Dispatcher.Invoke(() => progressBar.Value += 2, DispatcherPriority.Background));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.