本文介绍了获取源依赖项属性的绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取源代码上的绑定,BindingOperations.GetBinding仅适用于目标依赖项属性.

[更新]
让我尝试重述我的问题:

How do I get hold of a binding on the source, BindingOperations.GetBinding only works on target dependency properties.

[Update]
Let me try to rephrase my problem:

public class Alias : DependencyObject
{
public Int16 Int16
{
get { return (Int16)GetValue(Int16Property); }
set { SetValue(Int16Property, value); }
}

public static DependencyProperty Int16Property =
DependencyProperty.Register(
"Int16",
typeof(Int16),
typeof(Alias),
new PropertyMetadata(OnInt16Changed));

private static void OnInt16Changed(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
var sender = (Alias)d;

BindingExpressionBase binding = BindingOperations.GetBindingExpressionBase(
sender,
Int16Property);

var error = new ValidationError(new MyValidationRule(), binding);
Validation.MarkInvalid(binding, error);
}
}
}



类Alias是绑定上的源,其中目标是UI元素.问题在于BindingOperations.GetBindingExpressionBase无法获取绑定,因为依赖项属性Int16Property是绑定的源,而不是目标.

所以问题是,如果我知道source属性,如何获得绑定?
[/Update]



The class Alias is a source on a binding, where the target is a UI element. The problem is that BindingOperations.GetBindingExpressionBase doesn''t get me the binding since the dependency property Int16Property is the source on the binding, and not the target.

So the question is, how do I get hold of the binding if I know the source property?
[/Update]

推荐答案

var binding = new Binding();
binding.Source = myObject;


路径属性指定源的属性.
(可选)myObject实现INotifyPropertyChanged,因此更改会自动更新.
使用BindingOperations.SetBinding可以为DependencyObject设置此绑定:


The Path-property specifies the property of the source.
Optionally myObject implements INotifyPropertyChanged, so changes are updated automatically.
With BindingOperations.SetBinding you can set this Binding for a DependencyObject:

BindingOperations.SetBinding(this, ContentControl.ContentProperty, binding);



绑定仅以DependencyObject为目标,源可以是任何东西.
如果要将DependencyObject绑定到对象(即相反),请将Mode设置为BindingMode.OneWayToSource



Bindings only work with a DependencyObject as target, the source can be anything.
If you want to bind a DependencyObject to an object (i.e. the other way round), set Mode to BindingMode.OneWayToSource


这篇关于获取源依赖项属性的绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:52