Monday, 23 April 2012

PropertyPathHelper

Ever needed to get the value from a binding in code?   Well here you go.

public static class PropertyPathHelper
{
private static readonly Dummy _dummy = new Dummy();

public static object GetValue(object source, string propertyPath)
{
var binding = new Binding(propertyPath)
{
Mode = BindingMode.OneTime,
Source = source
};
BindingOperations.SetBinding(_dummy, Dummy.ValueProperty, binding);
return _dummy.GetValue(Dummy.ValueProperty);
}

private class Dummy : DependencyObject
{
public static readonly DependencyProperty ValueProperty =
DependencyProperty.Register("Value",
typeof (object),
typeof (Dummy),
new PropertyMetadata(null));
}
}
Thanks to Thomas Levesque for his answer on Stack Overflow:
http://stackoverflow.com/questions/3577802/wpf-getting-a-property-value-from-a-binding-path

No comments:

Post a Comment