WPF-有什么办法以编程方式评估绑定?

Cha*_*les 5 wpf binding

有谁知道如何获取与绑定关联的当前值?最近我遇到一个问题,我想获取与WPFToolKit DataGrid中特定单元格关联的值-因此我创建了一个函数,该函数获取Path字符串,分割为“。”。并尝试在循环中使用PropertyDescriptor,尝试获取绑定值。当然有更好的方法了:)。如果有人能指出正确的方向,我将永远爱你。

谢谢,

查尔斯

Sve*_*ven 1

由于给定的答案链接现在只能在 webarchive 上找到,我复制了那里给出的答案:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

例子:

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;
         }
     }
 }
Run Code Online (Sandbox Code Playgroud)