Tag: WPF/バインディング
public static T GetValue<T>(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 < pathParts.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; }
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)); } }