110,539
社区成员
发帖
与我相关
我的任务
分享
Dispatcher.BeginInvoke(DispatcherPriority.Normal, (ThreadStart)delegate()
{
// todo。。。。。
});
或者
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(()=>{
// todo。。。。。
}));
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就能支持多线程了。