如您在WPF
应用程序中所了解的,如果您想要将某些特定类的属性绑定到控件的属性,则必须实现该类的接口INotifyPropertyChanged
。如何将普通类动态地转换为c#
现在考虑我们有很多正常的类没有实现INotifyPropertyChanged
。他们是非常简单的类如下面的例子:
public class User : ModelBase
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
// ...
}
例如我想将UserName
绑定到一个TextBox
,所以我应该写另一个新User
类,它实现INotifyPropertyChanged
这样的:
public class User : INotifyPropertyChanged
{
public string Password { get {return _Password}}
set {_Password=value;OnPropertyChanged("Password");}
// ... Id and UserName properties are implemented like Password too.
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
// ...
}
现在我的问题是,那里是否存在或者你知道任何机制或技巧来简化?
认为我们有超过100个模型,也许他们会改变。
我在想一个办法,像使用普通类做(编辑):
public class BindableClass<NormalClass> { ...adding ability to bind instructions using reflection... }
NormalClass NormalInstance = new NormalClass();
// simple class, does not implemented INotifyPropertyChanged
// so it doesn't support binding.
BindableClass<NormalClass> BindableInstance = new BindableClass<NormalClass>();
// Implemented INotifyPropertyChanged
// so it supports binding.
当然,我不知道这是好办法还是不行!这只是一个想法来澄清我的问题。
请不要告诉我,没有办法或不可能!有数百个模型!
谢谢。
阿里,会不会使用MVVM和引入视图模型层是一个更好的解决方案?您确定要在模型上使用这种(以UI为中心)更改通知功能吗? – Alan
你不需要实现INotifyPropertyChanged来进行绑定。您只需要将INotifyPropertyChanged通知给用户界面以通知更改。 – Paparazzi
@Alan,我最后的选择是它。但我会避免重复。考虑到ViewModels实现,我们应该再次定义模型类,并附带一些额外的指令,例如INotifyPropertyChanged。 –