wpfbindingmarkup-extensions

WPF - Getting a property value from a binding path


if I have an object say called MyObject, which has a property called MyChild, which itself has a property called Name. How can I get the value of that Name property if all I have is a binding path (i.e. "MyChild.Name"), and a reference to MyObject?

MyObject
  -MyChild
    -Name

Solution

  • I found a way to do this, but it's quite ugly and probably not very fast... Basically, the idea is to create a binding with the given path and apply it to a property of a dependency object. That way, the binding does all the work of retrieving the value:

    public static class PropertyPathHelper
    {
        public static object GetValue(object obj, string propertyPath)
        {
            Binding binding = new Binding(propertyPath);
            binding.Mode = BindingMode.OneTime;
            binding.Source = obj;
            BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
            return _dummy.GetValue(Dummy.ValueProperty);
        }
    
        private static readonly Dummy _dummy = new Dummy();
    
        private class Dummy : DependencyObject
        {
            public static readonly DependencyProperty ValueProperty =
                DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
        }
    }