2010-07-19 35 views
3

說我有下面的代碼:如何更新一個WPF綁定立即

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

在這一點上,c.Content將返回null。

有沒有辦法強制綁定的評估,以便c.Content返回「測試」?

回答

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

+1非常好的洞察的東西,我不知道的,並意味着我不得不放棄在我有一個單元測試場景。高超。我將建議在設置綁定之前設置DataContext,而現在我不打擾它! :) – 2010-07-19 14:37:30

+0

更好: c.Dispatcher.Invoke(新的ThreadStart(委託{}),DispatcherPriority.Render); – 2010-07-19 18:06:10