Click here to Skip to main content
15,887,946 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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:

C#
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);
}
}
}


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]
Posted
Updated 28-Oct-11 2:49am
v2

1 solution

Use the constructor of Binding and set the source manually:
C#
var binding = new Binding();
binding.Source = myObject;

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:
C#
BindingOperations.SetBinding(this, ContentControl.ContentProperty, binding);


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
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900