如何使WPF数据绑定重构安全吗? [英] How do I make WPF data bindings refactor safe?

查看:173
本文介绍了如何使WPF数据绑定重构安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,我通过我的第一个WPF项目的工作,我喜欢我所看到为止。还有更多的学习曲线比我的预期,但仍然WPF是pretty的凉爽。不过,我挣扎与数据绑定的概念一点点。一个具体的问题,我是怎么让我的数据绑定声明重构安全吗?考虑这个例子。

So I am working through my first WPF project and I am liking what I see so far. There was more of learning curve than what I anticipated, but nevertheless WPF is pretty cool. However, I am struggling a little bit with the data binding concepts. One specific question I have is how do I make my data binding declarations refactor safe? Consider this example.

public class MyDataObject
{
  public string FooProperty { get; set; }
}

void Bind() 
{
  var gridView = myListView.View as GridView;
  gridView.Columns.Clear();
  gridView.Columns.Add(
    new GridViewColumn() 
      { 
        Header = "FooHeader", 
        DisplayMember = new Binding("FooProperty")
      }
    );
  List<MyDataObject> source = GetData();
  myListView.ItemsSource = source;
}

那么,如果我重新命名FooProperty我的数据对象到别的东西?数据绑定将是无效的,我不会得到一个编译错误,因为绑定是通过纯文本声明。有没有一种方法,使结合多一点的重构安全吗?

So what if I rename the FooProperty on my data object to something else? The data binding will be invalid and I will not get a compile error since the binding was declared via text only. Is there a way to make the binding a little more refactor safe?

推荐答案

您可以使用lambda EX pression到前preSS属性的名称,而不是直接使用的名称:

You could use a lambda expression to express the property name, rather than using the name directly :

    protected static string GetPropertyName<TSource, TResult>(Expression<Func<TSource, TResult>> expression)
    {
        if (expression.NodeType == ExpressionType.Lambda && expression.Body.NodeType == ExpressionType.MemberAccess)
        {
            PropertyInfo prop = (expression.Body as MemberExpression).Member as PropertyInfo;
            if (prop != null)
            {
                return prop.Name;
            }
        }
        throw new ArgumentException("expression", "Not a property expression");
    }

您会使用这样的:

...
DisplayMember = new Binding(GetPropertyName((MyDataObject o) => o.FooProperty))
...

确定,这是一个有点冗长......如果你想要的东西更短,你还可以创建一个辅助方法:

OK, it's a bit verbose... If you want something shorter, you could also create a helper method :

public Binding CreateBinding<TSource, TResult>(Expression<Func<TSource, TResult>> expression)
{
    return new Binding(GetPropertyName(expression))
}

...
DisplayMember = CreateBinding((MyDataObject o) => o.FooProperty)
...

通过这种方式,重构应正常工作,如果您重命名的属性(除当然XAML ...)

That way, the refactoring should work fine if you rename the property (except in the XAML of course...)

这篇关于如何使WPF数据绑定重构安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆