在 InitializeComponents 之后的 Window 构造函数中,我需要创建一个对象并将其绑定到数据网格。由于创建对象花费了太多时间,因此窗口需要一段时间才能显示出来。所以我决定将对象的创建移到后台线程,并通过执行 dispatcher.invoke 来“委托”到 UI 线程来执行绑定。但这失败了。
奇怪的是,如果我尝试设置我在 Dispatcher.invoke 中的矩形的可见性,它可以工作,但 DataGrid.setbinding 不行!有任何想法吗?我在后台工作人员和线程启动中尝试过同样的事情,但我一直收到同样的错误。我无法访问 DataGrid 对象,即使它发生在调度程序调用委托中。在我对它的工作原理的理解中,我肯定会遗漏一些东西。任何建议将不胜感激。谢谢!
StartupDelegate s = new StartupDelegate(CreateModel);
s.BeginInvoke(delegate(IAsyncResult aysncResult) { s.EndInvoke(aysncResult); }, null);
internal CreateModel()
{
Model d = new Model();
Dispatcher.Invoke( DispatcherPriority.Normal,
new Action<Model>(
delegate(Model d1)
{
mModel = d1; // mModel is a property defined in Window
Binding b = new Binding();
b.Source = mModel;
MainDataGrid.SetBinding(TreeView.ItemsSourceProperty, mainb); // << dies here with - The calling thread cannot access this object because a different thread owns it.
}
}
更新: 最终使用了只运行一次的调度程序计时器。将绑定代码放在其 Tick 委托中是可行的。但我仍然很好奇为什么上面的代码没有。