Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you evaluate a PropertyPath against an object *without* using a binding? (i.e. what does a binding itself use?)

Tags:

c#

binding

wpf

Note: To those who voted to close this. There's a specific reason I added the note. The solutions found here offer up using a binding against a dummy object/property, but as I specifically called out, I am not looking for a solution that uses binding. I'm trying to utilize/uncover the existing mechanism that bindings use without re-inventing the wheel. That's why I posted this with that note calling out that this is not in fact a duplicate. I have now edited the title to clarify this.

When applying a binding, you're essentially saying 'bind property path 'x' of source object 'a' to property path 'y' of target object 'b''. The binding itself specifies a source and a PropertyPath. It is then 'bound' to the target object's property.

However, I'm trying to evaluate the path directly against a source object and storing that in a variable.

Note: Yes I know I can create a dummy target class with a property of type Object and bind to that, then inspect it for a value, as several other answers here on StackOverflow and elsewhere say (see here for that solution), but I'm trying to avoid binding altogether. I'm looking for what the binding class does internally with the source and path.

var sourceObject = new Foo();
var propertyPath = new PropertyPath("Some.Property.Relative.To.Foo");

// What is equivalent to 'var pathValue = sourceObject.Some.Property.Relative.To.Foo;'
var pathValue = ???
like image 841
Mark A. Donohoe Avatar asked Dec 29 '25 02:12

Mark A. Donohoe


1 Answers

Binding parses the PropertyPath (which is basically just a string) and finds the property and it's value via reflection.

You can do it yourself: simplest method would be to split the path by '.' and search properties by name recursively. But there is also a simple method that does it if you add reference to System.Web: DataBinder.Eval

Example:

var pathValue = DataBinder.Eval(sourceObject, propertyPath.Path)
like image 195
teemu Avatar answered Dec 30 '25 15:12

teemu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!