2012-10-22 47 views
0

我有一個TextBox(TB1),它的Text值綁定到另一個TextBox(TB2),使用ElementName =「TB2」和Path =「Text」。複製ElementName綁定

然後我有第三個文本框(TB3),我在TB1後面的代碼中設置綁定,我希望我可以編輯TB3,並且TB1也會反映由於綁定(理論上)所有人都一樣。

我可以編輯TB1和TB2更新(反之亦然),但TB3從不顯示/更新值。

我只能認爲這是因爲TB1綁定使用ElementName而不是DependencyProperty?

是否可以複製使用ElementName綁定的元素的綁定?

<TextBox Name="TB1"> 
    <Binding ElementName="TB2" Path="Text" UpdateSourceTrigger="PropertyChanged"/> 
</TextBox> 
<TextBox Name="TB2"> 
    <Binding Path="Name" UpdateSourceTrigger="PropertyChanged"/> 
</TextBox> 

然後在後面的代碼,我有:

BindingExpression bindExpression = TB1.GetBindingExpression(TextBox.TextProperty); 
if (bindExpression != null && bindExpression.ParentBinding != null && bindExpression.ParentBinding.Path != null) 
{ 
    TB3.DataContext = TB1.DataContext; 
    TB3.SetBinding(TextBox.TextProperty, bindExpression.ParentBinding); 
} 

通常只發現測試剛纔說這樣做的工作,如果同樣的XAML中。但是,我有TB3在它自己的窗口如下,並且文本框永遠不會正確綁定..我錯過了什麼?

if (bindExpression != null && bindExpression.ParentBinding != null && bindExpression.ParentBinding.Path != null) 
{ 
    PopupWindow wnd = new PopupWindow(); 
    wnd.DataContext = TB1.DataContext; 
    wnd.TB3.SetBinding(TextBox.TextProperty, bindExpression.ParentBinding); 
    wnd.Show(); 
} 

我不是100%肯定,爲什麼,但這樣做有問題,這似乎做同樣的綁定,SetBinding但被設置爲DataItem的來源,但它給了我所需要的結果...謝謝Klaus78 ..

if (bindExpression != null && bindExpression.ParentBinding != null && bindExpression.ParentBinding.Path != null) 
    { 
     PopupWindow wnd = new PopupWindow(); 
     Binding b = new Binding(); 
     b.Source = bindExpression.DataItem; //TB1; 
     b.Path = new PropertyPath("Text"); 
     b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; 
     wnd.TB3.SetBinding(TextBox.TextProperty, b); 
     wnd.Show(); 
    } 

回答

1

在新的窗口中,您綁定TB3.TextTB2.Text

在實踐TB3.Text你有一個綁定OBJET其中Element=TB2Path=Text。問題是在新窗口的可視化樹中沒有名稱爲TB2的元素,因此如果您查看Visual Studio輸出調試,則會出現綁定錯誤。

另請注意TB1.DataContext爲空。另一方面,這個命令是無用的,因爲綁定類已經具有綁定源的屬性集合Element

我認爲你不能簡單地將綁定從TB1複製到TB3。無論如何,你需要創建一個TB3像

Window2 wnd = new Window2(); 
Binding b = new Binding(); 
b.Source = TB1; 
b.Path = new PropertyPath("Text"); 
wnd.TB3.SetBinding(TextBox.TextProperty, b); 
wnd.Show(); 

一個新的綁定對象可以像一些代碼對你有所幫助?

+0

謝謝Klaus78,這導致我的解決方案...請參閱編輯的問題。 – gas828

相關問題