C# Wpf ItemSource没有';t更新自定义控件中的可视控件
我有一个带有itemsSource绑定的自定义控件:C# Wpf ItemSource没有';t更新自定义控件中的可视控件,c#,wpf,C#,Wpf,我有一个带有itemsSource绑定的自定义控件: private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue) { Results.Clear(); foreach (var check in newValue) { Results.Add(check as Check); } }
private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
Results.Clear();
foreach (var check in newValue)
{
Results.Add(check as Check);
}
}
protected ObservableCollection<Check> results = new ObservableCollection<Check>();
public ObservableCollection<Check> Results
{
get { return results; }
set { results = value; }
}
我调用一个在主视图show方法中计算支票的类:
Thread t = new Thread(new ThreadStart(
delegate
{
Dispatcher.Invoke(DispatcherPriority.Normal, new Action<ResultCtrl>(AddIn.Services.Results.Comprobaciones), resultCtrl);
}
));
t.Start();
Thread t=新线程(新线程开始(
代表
{
Invoke(DispatcherPriority.Normal,新操作(AddIn.Services.Results.Comprobaciones),resultCtrl);
}
));
t、 Start();
在AddIn.Services.Results.Comprobaciones中,我会:
resultCtrl.ItemsSource = new ObservableCollection<Check>(AddIn.Document.Results);
resultCtrl.ItemsSource=新的ObservableCollection(AddIn.Document.Results);
每一张支票。每次这样做时,我都会看到ItemsSource是如何变化的,但只有在AddIn.Services.Results.Comprobaciones结束时才会更新。我试图执行UpdateLayout()和Items.Refresh(),但没有任何效果
有什么想法吗?此代码:
Thread t = new Thread(new ThreadStart(/* ... */);
t.Start();
创建一个完全无用的线程,因为它所做的一切都是对UI线程的调度程序的阻塞调用。换句话说,99.999…%的时间在UI线程上运行。你可以很容易地写下:
AddIn.Services.Results.Comprobaciones();
同样的结果
为了从多线程中获得任何好处,您必须重写代码。我不知道您的Comprobaciones
方法是什么样子,但是,很明显,您应该调用Dispatcher.Invoke
,只有在您需要更新UI中的某些内容时才调用
还要注意的是,在大多数情况下,您不应该直接创建Thread
实例。考虑使用(而不是通过代码> ASYNC/<代码> />代码>等待<代码>,如果你的目标是.NET 4.5),谢谢你的回答。AddIn.Services.Results.Comprobaciones();花点时间,这就是为什么我需要在其他线程。我想让AddIn.Services.Results.Comprobaciones()的视图可见并被填充;。因此,在后台线程中运行Comprobaciones
。但不要在调度程序中运行它。调用。可能,将这一行resultCtrl.ItemsSource=newObservableCollection(AddIn.Document.Results)换行会很困难调用调度程序中的code>。同样,我对Comprobaciones
的内容一无所知。可能还有另一个代码,应该在UI线程上运行。Comprobaciones看起来像:if(establishmentsChecks()){resultCtrl.ItemsSource=new ObservableCollection(AddIn.Document.Results);if(roomsChecks()){resultCtrl.ItemsSource=new ObservableCollection(AddIn.Document.Results);我希望在每次执行resultCtrl.ItemsSource=new ObservableCollection(AddIn.Document.Results)时更新visual;但仅在方法完成时更新
Thread t = new Thread(new ThreadStart(/* ... */);
t.Start();
AddIn.Services.Results.Comprobaciones();