是否可以在不知道依赖项属性名称的情况下从代码中创建两个依赖项属性之间的绑定?换句话说,我有2个DependencyProperty实例和2个DependencyObject实例,我想在它们之间创建一个Binding。
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);
如果我们不设置Path,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);