tags:

views:

240

answers:

1

I am writing a custom control, and I have a property path as string (think comboBox.SelectedValuePath).
What is the best way in code to evaluate this string for a arbitrary object?

I obviously can just parse it myself, but it is a hack, and I want the path to support everything comboBox.SelectedValuePath does (for consistency).

Result (thanks to Aran Mulholland):

Not sure about performance of this, but I do not care much for the performance right now.

public class BindingEvaluator {
    #region Target Class

    private class Target : DependencyObject {
        public static readonly DependencyProperty ResultProperty = DependencyProperty.Register(
            "Result", typeof(IEnumerable), typeof(BindingEvaluator)
        );

        public object Result {
            get { return this.GetValue(ResultProperty); }
            set { this.SetValue(ResultProperty, value); }
        }
    }

    #endregion

    public object GetValue(object source, string propertyPath) {
        var target = new Target();
        BindingOperations.SetBinding(target, Target.ResultProperty, new Binding(propertyPath) {
            Source = source,
            Mode = BindingMode.OneTime
        });
        return target.Result;
    }
}
+3  A: 

Create an object that has one dependency property of type object, set the binding on it with your property path as the path, and your arbitrary object as the source. the binding will execute and you can see what (if anything) is at the end of the property path. This is the only way i have found to do this kind of thing in code. you could write a recursive reflection engine that could follow a property path, but its already been done, we use it when we bind. take you five minutes to write :)

Aran Mulholland
Thanks, this works, adding resulting code to the question.
Andrey Shchekin
i use it as well in the odd case, i do wonder about the performance, but wpf uses binding all over the place so whats another one...
Aran Mulholland
WPF may have caching in place, while code in current form doesn't. At least caching the Binding between multiple calls can theoretically be better, but I do not care enough to verify unless I notice the slowdown. :)
Andrey Shchekin