How can I update WPF binding immediately

Let's 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 a binding evaluation so that c.Content returns "Test"?

+3
source share
1 answer

Only one message can be executed simultaneously in the user interface thread where this code is located. Data binding occurs with a certain priority in individual messages, so you need to make sure that this code:

object test = c.Content;

triggered after these data binding messages are completed. You can do this by queuing up a separate message with the same priority level (or lower) as the 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);
+6
source

Source: https://habr.com/ru/post/1755320/


All Articles