views:

43

answers:

1

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 point, c.Content will return null.

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

+3  A: 

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

HTH,
Kent

Kent Boogaart
+1 Very nice insight into something that I was not aware of, and meant that I had to give up on a unit-testing scenario I had. Superb. And I was going to suggest setting the DataContext before setting up the binding, which I will not bother with now! :)
chibacity
Even better:c.Dispatcher.Invoke (new ThreadStart (delegate{}), DispatcherPriority.Render);
tom greene