开发者

How can I update a WPF binding immediately

Say I have the following code:

ContentControl c = new ContentControl();
c.SetBinding (ContentControl.Content, new Binding());
c.DataContext = "Test";
object test = c.Content;

At this po开发者_StackOverflow社区int, c.Content will return null.

Is there a way to force the evaluation of the binding so that c.Content return "Test"?


Only one message can execute at a time on the UI thread, which is where this code is running. Data-binding happens at a specific priority in separate messages, so you'll need to ensure that this code:

object test = c.Content;

runs after those data binding messages are executed. You can do this by queuing a separate message with the same level of priority (or lower) as data binding:

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);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜