我有一个进度条,它绑定到“CurrProgress”和“Total”字段,如下所示:
<ProgressBar Height="29" HorizontalAlignment="Left" Margin="12,32,0,0" Name="pbSendingData" VerticalAlignment="Top" Width="346"">
<ProgressBar.Value>
<Binding ElementName="this" Path="CurrProgress" />
</ProgressBar.Value>
<ProgressBar.Maximum>
<Binding ElementName="this" Path="Total" />
</ProgressBar.Maximum>
</ProgressBar>
我还有一个“工作线程”,它在尝试保持 UI 响应时正在做繁重的工作:
private void worker_DoWork(object sender, DoWorkEventArgs e)
{
const int sizeOfPacket = 30;
Total = allEntries.Count();
var arrayOfEntries = Split(allEntries, sizeOfPacket); //Split array into small arrays
//Send parts to server separately:
foreach (var entries in arrayOfEntries)
{
svc.ProcessPMData(Globals.username, Globals.password, entries.ToArray());
CurrProgress += sizeOfPacket;
Thread.Sleep(100);
}
Thread.Sleep(100);
}
我确保“Total”和“CurrProgress”依赖属性是线程安全的(尽管我可能没有正确完成):
//Dependency properties:
public int CurrProgress
{
get
{
return (int)this.Dispatcher.Invoke(
DispatcherPriority.Background,
(DispatcherOperationCallback)delegate
{
return GetValue(CurrProgressProperty);
}, CurrProgressProperty);
}
set
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Background,
(SendOrPostCallback)delegate { SetValue(CurrProgressProperty, value); },
value);
}
}
public static readonly DependencyProperty CurrProgressProperty =
DependencyProperty.Register("CurrProgress", typeof(int), typeof(DataSender), new PropertyMetadata(0));
public int Total
{
get
{
return (int)this.Dispatcher.Invoke(
DispatcherPriority.Background,
(DispatcherOperationCallback)delegate
{
return GetValue(TotalProperty);
}, TotalProperty);
}
set
{
this.Dispatcher.BeginInvoke(DispatcherPriority.Background,
(SendOrPostCallback)delegate { SetValue(TotalProperty, value); },
value);
}
}
public static readonly DependencyProperty TotalProperty =
DependencyProperty.Register("Total", typeof(int), typeof(DataSender), new PropertyMetadata(0));
在尝试调试时,我首先尝试从即时窗口检查进度条的值:
pbSendingData.Value
我收到此错误消息...
这个错误是有道理的,所以我尝试了另一种方法:
this.Dispatcher.Invoke((Action)(() => { MessageBox.Show(pbSendingData.Minimum); }));
此时我发现即时窗口不支持 lambda 表达式。
监视窗口也无济于事:
在调试时,我想从不同线程的即时/监视窗口中获取 UI 组件的值。这可能吗?作为旁注,如果我的代码中有任何可耻的地方,我愿意接受建议。我对 WPF 有点陌生。