Guest User

Untitled

a guest
Apr 27th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.78 KB | None | 0 0
  1. private BindingExpression GetTextBinding()
  2. {
  3. return this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);
  4. }
  5.  
  6. var bindingExpression = GetTextBinding();
  7. object dataContextItem = bindingExpression.DataItem;
  8. PropertyPath relativePropertyPath = bindingExpression.ParentBinding.Path;
  9.  
  10. public static T GetValue<T>(this BindingExpression expression, object dataItem)
  11. {
  12. if (expression == null || dataItem == null)
  13. {
  14. return default(T);
  15. }
  16.  
  17. string bindingPath = expression.ParentBinding.Path.Path;
  18. string[] properties = bindingPath.Split('.');
  19.  
  20. object currentObject = dataItem;
  21. Type currentType = null;
  22.  
  23. for (int i = 0; i < pathParts.Length; i++)
  24. {
  25. currentType = currentObject.GetType();
  26. PropertyInfo property = currentType.GetProperty(properties[i]);
  27. if (property == null)
  28. {
  29. currentObject = null;
  30. break;
  31. }
  32. currentObject = property.GetValue(currentObject, null);
  33. if (currentObject == null)
  34. {
  35. break;
  36. }
  37. }
  38.  
  39. return (T)currentObject;
  40. }
  41.  
  42. public static class PropertyPathHelper
  43. {
  44. public static object GetValue(object obj, string propertyPath)
  45. {
  46. Binding binding = new Binding(propertyPath);
  47. binding.Mode = BindingMode.OneTime;
  48. binding.Source = obj;
  49. BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
  50. return _dummy.GetValue(Dummy.ValueProperty);
  51. }
  52.  
  53. private static readonly Dummy _dummy = new Dummy();
  54.  
  55. private class Dummy : DependencyObject
  56. {
  57. public static readonly DependencyProperty ValueProperty =
  58. DependencyProperty.Register("Value", typeof(object), typeof(Dummy), new UIPropertyMetadata(null));
  59. }
  60. }
Add Comment
Please, Sign In to add comment