如何使数据绑定类型安全并支持重构? [英] How to make Databinding type safe and support refactoring?
问题描述
当我希望将控件绑定到对象的属性时,必须将属性的名称提供为字符串。这不是很好,因为:
When I wish to bind a control to a property of my object, I have to provide the name of the property as a string. This is not very good because:
- 如果属性被删除或重命名,那么我不会收到编译器警告。
- 如果使用重构工具对属性进行重命名,则可能不会更新数据绑定。
- 如果属性的类型是错误的,例如将整数绑定到日期选择器,然后直到运行时我都不会出错。
是否有一个设计模式可以获取这样解决,但是仍然易于使用数据绑定吗?
Is there a design-pattern that gets round this, but still has the ease of use of data-binding?
(这是WinForms,ASP.NET和WPF以及其他系统中的问题。)
(This is a problem in WinForms, ASP.NET, and WPF and possibly other systems.)
我现在发现 C#中nameof()运算符的变通方法:类型安全数据绑定,它也是解决方案的一个很好的起点。
I have now found "workarounds for nameof() operator in C#: typesafe databinding" that also has a good starting point for a solution.
要在编译代码后使用后处理器,那么<a href=\"https://github.com/shiftkey/NotifyPropertyWeaver\" rel=\"nofollow noreferrer\"> NotifyPropertyWeaver 值得一看。
If you are willing to use a post processor after compiling your code, then NotifyPropertyWeaver is worth looking at.
有人用XML而不是C#进行绑定时,有人知道WPF的好解决方案吗?
Does anyone know of a good solution for WPF when the bindings are done in XML rather than C#?
推荐答案
感谢Oliver让我入门d我现在有一个既支持重构又是类型安全的解决方案。
Thanks to Oliver for getting me started I now have a solution that both supports refactoring and is type safe. It also let me implement INotifyPropertyChanged so it copes with properties being renamed.
它的用法类似于:
checkBoxCanEdit.Bind(c => c.Checked, person, p => p.UserCanEdit);
textBoxName.BindEnabled(person, p => p.UserCanEdit);
checkBoxEmployed.BindEnabled(person, p => p.UserCanEdit);
trackBarAge.BindEnabled(person, p => p.UserCanEdit);
textBoxName.Bind(c => c.Text, person, d => d.Name);
checkBoxEmployed.Bind(c => c.Checked, person, d => d.Employed);
trackBarAge.Bind(c => c.Value, person, d => d.Age);
labelName.BindLabelText(person, p => p.Name);
labelEmployed.BindLabelText(person, p => p.Employed);
labelAge.BindLabelText(person, p => p.Age);
person类显示如何以类型安全的方式(或查看此答案,以了解实现INotifyPropertyChanged的另一种不错的方法, ActiveSharp-自动INotifyPropertyChanged 看起来也不错):
The person class shows how to implemented INotifyPropertyChanged in a type safe way (or see this answer for a other rather nice way of implementing INotifyPropertyChanged, ActiveSharp - Automatic INotifyPropertyChanged also looks good ):
public class Person : INotifyPropertyChanged
{
private bool _employed;
public bool Employed
{
get { return _employed; }
set
{
_employed = value;
OnPropertyChanged(() => c.Employed);
}
}
// etc
private void OnPropertyChanged(Expression<Func<object>> property)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(BindingHelper.Name(property)));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
WinForms绑定帮助器类中有很多东西可以使它们全部工作:
The WinForms binding helper class has the meat in it that makes it all work:
namespace TypeSafeBinding
{
public static class BindingHelper
{
private static string GetMemberName(Expression expression)
{
// The nameof operator was implemented in C# 6.0 with .NET 4.6
// and VS2015 in July 2015.
// The following is still valid for C# < 6.0
switch (expression.NodeType)
{
case ExpressionType.MemberAccess:
var memberExpression = (MemberExpression) expression;
var supername = GetMemberName(memberExpression.Expression);
if (String.IsNullOrEmpty(supername)) return memberExpression.Member.Name;
return String.Concat(supername, '.', memberExpression.Member.Name);
case ExpressionType.Call:
var callExpression = (MethodCallExpression) expression;
return callExpression.Method.Name;
case ExpressionType.Convert:
var unaryExpression = (UnaryExpression) expression;
return GetMemberName(unaryExpression.Operand);
case ExpressionType.Parameter:
case ExpressionType.Constant: //Change
return String.Empty;
default:
throw new ArgumentException("The expression is not a member access or method call expression");
}
}
public static string Name<T, T2>(Expression<Func<T, T2>> expression)
{
return GetMemberName(expression.Body);
}
//NEW
public static string Name<T>(Expression<Func<T>> expression)
{
return GetMemberName(expression.Body);
}
public static void Bind<TC, TD, TP>(this TC control, Expression<Func<TC, TP>> controlProperty, TD dataSource, Expression<Func<TD, TP>> dataMember) where TC : Control
{
control.DataBindings.Add(Name(controlProperty), dataSource, Name(dataMember));
}
public static void BindLabelText<T>(this Label control, T dataObject, Expression<Func<T, object>> dataMember)
{
// as this is way one any type of property is ok
control.DataBindings.Add("Text", dataObject, Name(dataMember));
}
public static void BindEnabled<T>(this Control control, T dataObject, Expression<Func<T, bool>> dataMember)
{
control.Bind(c => c.Enabled, dataObject, dataMember);
}
}
}
C#3.5中的新内容,并显示了可能的结果。现在,如果只有我们卫生宏,那么Lisp程序员可能会停止称我们为二等公民)
This makes use of a lot of the new stuff in C# 3.5 and shows just what is possible. Now if only we had hygienic macros lisp programmer may stop calling us second class citizens)
这篇关于如何使数据绑定类型安全并支持重构?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!