2011-11-28 24 views
0

問題描述:在我的Silverlight應用程序(4.0)中,我有一個TextBox控件,該背景綁定到某個源屬性。我爲TextBox控件創建了一個行爲。在我的行爲裏面,我想要綁定這個綁定,然後「重定向到」其他目標(比如說,對於行爲本身)。換句話說,當背景綁定的源屬性發生變化時,而不是更新TextBox控件的屬性,我想更新一些其他目標屬性。怎麼做?我試圖反思,但它不允許在私人領域的SL ...如何更換綁定目標(silverlight 4.0)

在此先感謝。

回答

0

我不知道你爲什麼要「重定向」。如果文本框中的文本更改,它仍然可以嗎?如果你試圖做綁定到屏幕上的其它元素,你可以使用元件結合的TB1文本框失去焦點後會發生:

<StackPanel> 
<TextBox x:Name="tb1" /> 
<TextBox Text="{Binding ElementName=tb1, Source=Text}" /> 
</StackPanel> 

在行爲,請我們TextChanged事件和捕捉它那裏。

public class TextBoxBehavior : Behavior<TextBox> 
{ 
/// <summary> 
/// Called after the Behavior is attached to an AssociatedObject. 
/// </summary> 
/// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks> 
protected override void OnAttached() 
{ 
base.OnAttached(); 
this.AssociatedObject.TextChanged += new TextChangedEventHandler(AssociatedObject_TextChanged); 
} 

/// <summary> 
/// Called after the Behavior is detached from an AssociatedObject. 
/// </summary> 
/// <remarks>Override this to hook up functionality to the AssociatedObject.</remarks> 
protected override void OnDetaching() 
{ 
base.OnDetaching(); 
this.AssociatedObject.TextChanged -= new TextChangedEventHandler(AssociatedObject_TextChanged); 
} 

void AssociatedObject_TextChanged(object sender, TextChangedEventArgs e) 
{ 
if(!string.IsNullOrEmpty(this.AssociatedObject.Text)) 
{ 
string enteredValue = this.AssociatedObject.Text; 
// do what you want with the entered value 
} 

// if you want to reset it.. this.AssociatedObject.Text = string.Empty; 
} 
} 
+0

要對齊:我無法控制XAML。我試圖開發一個行爲,這將影響任何TextBox,無論它應用於何處。在我提供的示例中,用戶在其XAML中設置了對TextBox背景的綁定。但是,在他應用我的行爲後,我希望(從行爲內部)採取該背景,並將其更改爲其他內容(比方說,我想用另一個畫筆創建原始背景)。如果我知道如何從綁定的DependencyProperty中提取當前值,那將是勝利的一半。我試圖使用GetValue - 什麼都不返回。 – Illidan

1

可以使用FrameworkElement.GetBindingExpression獲取現有Binding。這裏有一個例子:

FrameworkElement yourControl = null; // the code to get the control goes here 
BindingExpression bindingExpression = 
    yourControl.GetBindingExpression(TextBox.Background); 
Binding binding = bindingExpression.ParentBinding; // it's your binding 

然後,創建一個新的Binding對象,設置其屬性(如果需要改變目標),並使用SetBinding進行安裝。

UPDATE

現在關於綁定源。

請注意,僅當您明確設置此屬性時,Source屬性纔會爲非null。

Binding源其他選項包括:

  1. 特定元素:用於如果Binding.ElementName屬性設置
  2. 模板控制:如果Binding.RelativeSource被設置爲RelativeSourceMode=RelativeSourceMode.TemplatedParent
  3. 結合靶控制中使用:如果Binding.RelativeSource設置爲RelativeSource,則使用Mode=RelativeSourceMode.TemplatedParent
  4. DataContext:如果兩者都不爲Source,也不適用前3個選項。

如果你想克隆Binding,你應該檢查所有這些選項。

但是,如果您只需要數據項,則最好使用BindingExpression.DataItem屬性,該屬性應返回作爲綁定源的實際數據項。

+0

帕維爾:我試過,但由於某種原因,返回綁定的「源」爲空。防止重用此綁定或建立另一個基於此...順便說一句,返回綁定的路徑看起來非常好。 – Illidan

+0

@Illidan請檢查我更新的答案。 –

+0

BindingExpression.DataItem爲null,就像所有其他屬性一樣。你在Silverlight 4上測試了你的答案嗎? – Illidan