How to resolve bound object from bindingexpression with WPF?

前端 未结 5 1231
再見小時候
再見小時候 2020-12-14 17:17

Hi does anyone know if there are any inbuilt classes for resolving a bound object from a bindingexpression and it\'s DataItem and property path?

I\'m attempting to w

5条回答
  •  半阙折子戏
    2020-12-14 17:56

    Below is a quick implementation for an extension method that will do just what you are looking for. I couldn't find anything related to this either. The method below will always return null if for some reason the value cannot be found. The method won't work when the path includes []. I hope this helps!

    public static T GetValue(this BindingExpression expression, object dataItem)            
    {
        if (expression == null || dataItem == null)
        {
            return default(T);
        }
    
        string bindingPath = expression.ParentBinding.Path.Path;
        string[] properties = bindingPath.Split('.');
    
        object currentObject = dataItem;
        Type currentType = null;
    
        for (int i = 0; i < properties.Length; i++)
        {
            currentType = currentObject.GetType();                
            PropertyInfo property = currentType.GetProperty(properties[i]);
            if (property == null)
            {                    
                currentObject = null;
                break;
            }
            currentObject = property.GetValue(currentObject, null);
            if (currentObject == null)
            {
                break;
            }
        }
    
        return (T)currentObject;
    }
    

提交回复
热议问题