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

时间:2009-04-01 01:44:40

标签: wpf binding

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

谢谢,

查尔斯

1 个答案:

答案 0 :(得分:0)

由于答案的给定链接现在仅在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);
    }
}

示例:

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;
         }
     }
 }