問題描述:在我的Silverlight應用程序(4.0)中,我有一個TextBox控件,該背景綁定到某個源屬性。我爲TextBox控件創建了一個行爲。在我的行爲裏面,我想要綁定這個綁定,然後「重定向到」其他目標(比如說,對於行爲本身)。換句話說,當背景綁定的源屬性發生變化時,而不是更新TextBox控件的屬性,我想更新一些其他目標屬性。怎麼做?我試圖反思,但它不允許在私人領域的SL ...如何更換綁定目標(silverlight 4.0)
在此先感謝。
問題描述:在我的Silverlight應用程序(4.0)中,我有一個TextBox控件,該背景綁定到某個源屬性。我爲TextBox控件創建了一個行爲。在我的行爲裏面,我想要綁定這個綁定,然後「重定向到」其他目標(比如說,對於行爲本身)。換句話說,當背景綁定的源屬性發生變化時,而不是更新TextBox控件的屬性,我想更新一些其他目標屬性。怎麼做?我試圖反思,但它不允許在私人領域的SL ...如何更換綁定目標(silverlight 4.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;
}
}
可以使用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
源其他選項包括:
Binding.ElementName
屬性設置Binding.RelativeSource
被設置爲RelativeSource
與Mode=RelativeSourceMode.TemplatedParent
Binding.RelativeSource
設置爲RelativeSource
,則使用Mode=RelativeSourceMode.TemplatedParent
DataContext
:如果兩者都不爲Source
,也不適用前3個選項。如果你想克隆Binding
,你應該檢查所有這些選項。
但是,如果您只需要數據項,則最好使用BindingExpression.DataItem
屬性,該屬性應返回作爲綁定源的實際數據項。
要對齊:我無法控制XAML。我試圖開發一個行爲,這將影響任何TextBox,無論它應用於何處。在我提供的示例中,用戶在其XAML中設置了對TextBox背景的綁定。但是,在他應用我的行爲後,我希望(從行爲內部)採取該背景,並將其更改爲其他內容(比方說,我想用另一個畫筆創建原始背景)。如果我知道如何從綁定的DependencyProperty中提取當前值,那將是勝利的一半。我試圖使用GetValue - 什麼都不返回。 – Illidan