【发布时间】:2011-07-10 04:53:32
【问题描述】:
我已经阅读了很多关于绑定和 GUI 控件的线程亲和性的帖子、文章等。有些帖子人们不想使用Dispatcher。
我还有一个同事避免在他的代码中使用 Dispatcher。我问他原因,但他的回答并不让我满意。他说,他不喜欢这种隐藏在课堂上的“魔法”。
嗯,我是以下课程的粉丝。
public class BindingBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private Dispatcher Dispatcher
{
#if SILVERLIGHT
get { return Deployment.Current.Dispatcher; }
#else
get { return Application.Current.Dispatcher; }
#endif
}
protected void RaisePropertyChanged<T>(Expression<Func<T>> expr)
{
var memberExpr = (MemberExpression)expr.Body;
string property = memberExpr.Member.Name;
var propertyChanged = PropertyChanged;
if (propertyChanged == null) return;
if (Dispatcher.CheckAccess())
propertyChanged.Invoke(this, new PropertyChangedEventArgs(property));
else
Dispatcher.BeginInvoke(() => RaisePropertyChanged(expr));
}
}
问题来了。有些人不想使用这样的课程有什么原因吗?也许我必须重新考虑这种方法。
你不得不承认,有一件奇怪的事情。 Dispatcher.CheckAccess() 被排除在 Intellisense 之外。也许因为这个事实,他们有点害怕。
问候
编辑:
好的,再举一个例子。考虑一个复杂的对象。作为示例的集合可能不是最好的主意。
public class ExampleVm : BindingBase
{
private BigFatObject _someData;
public BigFatObject SomeData
{
get { return _someData; }
set
{
_someData = value;
RaisePropertyChanged(() => SomeData);
}
}
public ExampleVm()
{
new Action(LoadSomeData).BeginInvoke(null, null); //I know - it's quick and dirty
}
private void LoadSomeData()
{
// loading some data from somewhere ...
// result is of type BigFatObject
SomeData = result; // This would not work without the Dispatcher, would it?
}
}
【问题讨论】:
标签: wpf silverlight data-binding