WPF學習筆記 - 資料繫結(在代碼中)

來源:互聯網
上載者:User

標籤:

在程式碼裡,有兩種設定綁定的方法,一種是調用FrameworkElement或FrameContentElement對象的SetBinding執行個體方法。

例如:

Public MainWindow()

{

InitializeCompnet();

 

Binding binding = new Binding();

//設定來源物件

binding.Source = treeview;

//設定源屬性

binding.Path = new PropertyPath("SelectedItem.Header");

//設定目標屬性

currentFolder.SetBinding(TextBlock.TextProperty, binding);

}

另一種是調用BindingOperations類的SetBingding靜態方法。可以向這個靜態方法傳遞與上面執行個體方法相同的對象,但是他的第一個參數表示目標對象。

例如:BindingOperations.SetBinding(currentFolder, TextBlock.TextProperty, binding);

靜態方法的好處是,第一個參數是一個DependencyObject對象,他支援對那些不是從FrameworkElement或FrameContentElement對象繼承而來的對象(如Freeable對象)進行資料繫結。

如果一個綁定在剩下的應用程式生命週期中已經沒有用了,可以在任何時候通過BindingOperations.ClearBinding斷開該綁定,要做的就是傳入一個目標對象和它的相依性屬性。例如:BindingOperations.ClearBinding(currentFolder, TextBlock.TextProperty);

BindingOperations.ClearAllBindings方法是移除所有的綁定。

例如:BindingOperations.ClearAllBindings(currentFolder);

另一種清除綁定的方法是直接為目標屬性設定一個新的值。

例如:currentFolder.Text = "I am no longer receiving updates.";

需要注意的是,這僅是清除單向綁定。ClearBinding方法相對而言更加靈活,因為它仍然允許相依性屬性以較低的優先順序從源那裡(如樣式觸發程序、屬性值繼承等)獲得值。

實際上ClearBinding內部調用的都是目標對象的ClearValue方法清除一個本地值。

 

http://blog.csdn.net/cs_oldhorse/article/details/6804567

WPF學習筆記 - 資料繫結(在代碼中)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.