因此,我通过我的第一个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...)
相关推荐
最新文章