2016-12-25 166 views
0

是否有可能在不知道依賴屬性名稱的情況下,從代碼創建兩個依賴項屬性之間的綁定?換句話說,我有2個DependencyProperty實例和2個DependencyObject實例,我想在它們之間創建一個綁定。無名綁定2依賴屬性

Binding newBinding = new Binding(); 
newBinding.Source = SourceDependencyObject; 
newBinding.Path = ???; // Get name from SourceDependencyProperty? 

BindingOperations.SetBinding(TargetDependencyObject, TargetDependencyProperty, newBinding); 
+0

任何更新?我的答案解決了你的問題嗎? –

回答

1

如果SourceDependencyObject是DependencyObject,看來我們應該能夠從SourceDependencyProperty獲取名稱並設置爲Binding.Path

例如:

TextBlock SourceDependencyObject = new TextBlock(); 
SourceDependencyObject.Text = "Hello"; 
TextBlock TargetDependencyObject = new TextBlock(); 
Binding myBinding = new Binding(); 
myBinding.Source = SourceDependencyObject; 
myBinding.Path = new PropertyPath("Text"); 
BindingOperations.SetBinding(TargetDependencyObject, TextBlock.TextProperty, myBinding); 
Debug.WriteLine(TargetDependencyObject.Text); 

如果我們不設置路徑時,TargetDependencyProperty將指向SourceDependencyObject。

所以如果SourceDependencyObject是string,int或其他類型。我們不需要設置Binding.Path

例如:

TextBlock SourceDependencyObject = new TextBlock(); 
SourceDependencyObject.Text = "Hello"; 
TextBlock TargetDependencyObject = new TextBlock(); 
Binding myBinding = new Binding(); 
myBinding.Source = SourceDependencyObject.Text; 
//myBinding.Path = new PropertyPath("Text"); 
BindingOperations.SetBinding(TargetDependencyObject, TextBlock.TextProperty, myBinding); 
Debug.WriteLine(TargetDependencyObject.Text);