说我有以下代码:
ContentControl c = new ContentControl();
c.SetBinding (ContentControl.Content, new Binding());
c.DataContext = "Test";
object test = c.Content;
Run Code Online (Sandbox Code Playgroud)
此时,c.Content将返回null.
有没有办法强制评估绑定,以便c.Content返回"测试"?
UI线程上一次只能执行一条消息,这是运行此代码的位置.数据绑定在单独的消息中以特定优先级发生,因此您需要确保此代码:
object test = c.Content;
Run Code Online (Sandbox Code Playgroud)
在执行这些数据绑定消息之后运行.您可以通过将具有与数据绑定相同的优先级(或更低)的单独消息排队来执行此操作:
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
770 次 |
| 最近记录: |