说我有以下代码:
ContentControl c = new ContentControl();
c.SetBinding (ContentControl.Content, new Binding());
c.DataContext = "Test";
object test = c.Content;
此时,c.Content将返回null。
有没有办法强制评估绑定,以便c.Content返回“Test”?
答案 0 :(得分:6)
UI线程上一次只能执行一条消息,这是运行此代码的位置。数据绑定在单独的消息中以特定优先级发生,因此您需要确保此代码:
object test = c.Content;
在执行这些数据绑定消息后运行。您可以通过将具有与数据绑定相同的优先级(或更低)的单独消息排队来执行此操作:
var c = new ContentControl();
c.SetBinding(ContentControl.ContentProperty, new Binding());
c.DataContext = "Test";
// this will execute after all other messages of higher priority have executed, and after already queued messages of the same priority have been executed
Dispatcher.BeginInvoke((ThreadStart)delegate
{
object test = c.Content;
}, System.Windows.Threading.DispatcherPriority.DataBind);