FrameworkElement.SetBinding(DependencyProperty, BindingBase) 方法

定義

使用提供的系結物件,將系結附加至 FrameworkElement

void SetBinding(DependencyProperty const& dp, BindingBase const& binding);
public void SetBinding(DependencyProperty dp, BindingBase binding);
function setBinding(dp, binding)
Public Sub SetBinding (dp As DependencyProperty, binding As BindingBase)

參數

dp
DependencyProperty

資料系結之屬性的相依性屬性識別碼。

binding
BindingBase

要用於 屬性的系結。

範例

這個範例會藉由呼叫 SetBinding ,建立物件上相依性屬性的系結。

// Create the source string.
string s = "Hello";

// Create the binding description.
Binding b = new Binding();
b.Mode = BindingMode.OneTime;
b.Source = s;

// Attach the binding to the target.
TextBlock MyText = new TextBlock();
MyText.SetBinding(TextBlock.TextProperty, b);

備註

這個方法是呼叫 BindingOperations.SetBinding的便利方法,傳遞目前實例做為 target 參數。

參數的類型 binding 基於相容性考慮而為BindingBase,但在Windows 執行階段您一律會傳遞Binding實例。 Binding 衍生自 BindingBase

參數 dp 會採用相依性屬性識別碼。 如需相依性屬性的詳細資訊,以及 DependencyProperty 值如何作為識別碼,請參閱 相依性屬性概觀

您可以系結至自訂相依性屬性或自訂附加屬性,因為參數傳遞的 dp 識別碼不一定是已定義的Windows 執行階段屬性。

從程式碼建立的系結是否能夠使用作用中的資料內容,取決於物件存留期考慮。 例如,從 XAML 設定的 DataCoNtext 值在剖析 XAML 之前將無法使用。 在此情況下,您可能想要使用 Loaded 處理常式從程式碼新增系結。

注意

SetBinding呼叫 方法並傳入新的Binding物件不一定會移除現有的系結。 相反地,您應該先呼叫 DependencyObject.ClearValue 方法,然後呼叫 SetBinding

系結至附加屬性

您可以將資料系結放在目標物件支援的任何附加屬性上。 技術上, DependencyObject 支援所有可能的附加屬性,但您通常只會在與該物件或案例相關的附加屬性上設定系結。 例如,只有在您預期目標專案具有將使用該資訊的Grid父系時,才會在Grid.Row上設定系結。 針對範例,請將 dp 參數指定為附加屬性擁有者類別 Grid.Row 上存在的相依性屬性識別碼, (該識別碼為 Grid.RowProperty) 。 您無法在目標上找到該識別碼,因為它是附加屬性。 如需附加屬性的詳細資訊,請參閱 附加屬性概觀

適用於

另請參閱