我有一个进度条,它绑定到“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>
我还有一个“工作人员线程”在尝试保持用户界面响应时做了很多工作:
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有点新鲜。
答案 0 :(得分:1)
您在进度条属性的Bindings中引用的“this”元素是什么元素?
我看到的大多数代码都使用来自工作线程的调度程序和委托,而不是属性getter / setter,因为这可能会导致一些丑陋的竞争条件和死锁或类似的讨厌的东西。
“DoWork”方法似乎属于BackGroundWorker类。为什么不使用“ReportProgress”功能?它包括线程同步......