Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF - Is there any way to programmatically evaluate a binding?

Tags:

binding

wpf

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

like image 605
Charles Avatar asked Nov 15 '22 16:11

Charles


1 Answers

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;
         }
     }
 }
like image 114
Sven Avatar answered Dec 23 '22 09:12

Sven