Does anyone know how to get the current value associated with a Binding? I ran into a problem recently where I wanted to get the value associated with a particular cell in the WPFToolKit DataGrid - so I created a function that gets the Path string, splits on '.' and tries uses PropertyDescriptor in a loop, trying to get the bound value. Surely there's a better way :). If anyone can point me in the right direction, I'll love you forever.
Thanks,
Charles
As the given link to the answer is nowadays only available on webarchive I duplicated the answer that was given there:
public static class DataBinder
{
private static readonly DependencyProperty DummyProperty = DependencyProperty.RegisterAttached(
"Dummy",
typeof(Object),
typeof(DependencyObject),
new UIPropertyMetadata(null));
public static object Eval(object container, string expression)
{
var binding = new Binding(expression) { Source = container };
return binding.Eval();
}
public static object Eval(this Binding binding, DependencyObject dependencyObject = null)
{
dependencyObject = dependencyObject ?? new DependencyObject();
BindingOperations.SetBinding(dependencyObject, DummyProperty, binding);
return dependencyObject.GetValue(DummyProperty);
}
}
Example:
public partial class PropertyPathParserDemo : Window
{
public PropertyPathParserDemo()
{
InitializeComponent();
Foo foo = new Foo() { Bar = new Bar() { Value = "Value" } };
this.Content = DataBinder.Eval(foo, "Bar.Value");
}
public class Foo
{
public Bar Bar
{
get;
set;
}
}
public class Bar
{
public string Value
{
get;
set;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With