首先我给ListView控件绑定一个List数据源,然后采用多线程对List数据源进行更新,有的时候就会触发以下错误(有时又不会)“某个ItemsControl与它的 项源不一致 ”

情况跟http://blog.csdn.net/alading2009/article/details/40626243里的差不多,但我用他的方法时,编译报错
“AddItem”的重载均与委托“System.Threading.ParameterizedThreadStart”不匹配
—- 30分
如果你的数据源需要用在多线程中,那么就应该重写你的Model定义。
一般Model需要实现了INotifyPropertyChanged后,才能通知绑定视图更新,而对于INotifyPropertyChanged接口,我们一般是这么写的:
一般Model需要实现了INotifyPropertyChanged后,才能通知绑定视图更新,而对于INotifyPropertyChanged接口,我们一般是这么写的:
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
然后在属性的Set方法中调用那个OnPropertyChanged方法来触发事件。
但现在是用在多线程中,因此那个方法必须要异步回调来触发,否则就会产生异常。方法如下:
public abstract class ModelBase : INotifyPropertyChanged
{
SynchronizationContext context;
public ModelBase(SynchronizationContext _context)
{
context = _context;
OnPropertyChanged = propertyName =>
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
context.Post(t => handler(this, new PropertyChangedEventArgs((string)t)), propertyName);
}
};
}
public ModelBase()
{
OnPropertyChanged = propertyName =>
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
};
}
public event PropertyChangedEventHandler PropertyChanged;
protected Action<string> OnPropertyChanged;
}
public class A : ModelBase
{
string _Name;
public string Name
{
get { return _Name; }
set
{
if(_Name != value)
{
_Name = value;
OnPropertyChanged("Name");
}
}
}
}
只要传递SynchronizationContext就能支持多线程了。
—- 10分
更新数据源为什么还要使用线程,完全感觉没必要。observableCollection 集合本来都支持数据更改。
改成这样试试
改成这样试试
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
// todo。。。。。
});
或者
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(()=>{
// todo。。。。。
}));
CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明WPF多线程:某个ItemsControl与它的 项源不一致!