在wpf中快速生成ViewModel属性? [英] Quickly generating ViewModel properties in wpf?
问题描述
阅读这篇文章后,在我的PersonViewModel
类:
public Jurisdiction CountryResidence
{
get
{
return Model.CountryResidence;
}
set
{
if (Model.CountryResidence == value)
return;
else
{
Model.CountryResidence = value;
base.OnPropertyChanged("CountryResidence");
}
}
}
public Jurisdiction CountryBirth
{
get
{
return Model.CountryBirth;
}
set
{
if (Model.CountryBirth == value)
return;
else
{
Model.CountryBirth = value;
base.OnPropertyChanged("CountryBirth");
}
}
}
我还有 CountryDomiciled
、CountryPassport
和 LegalJurisdiction
,它们都具有相同的格式.同样,我有很多 String
属性,所有这些属性都共享它们的格式.
I also have CountryDomiciled
, CountryPassport
and LegalJurisdiction
, all with the same format. Similarly, I have lots of String
properties, all of which share their format.
这会产生很多相同的代码!但是,我不知道如何使它更简洁.
This results in lots of samey code! However, I can't work out how to make this more concise.
是否有更好的方法来生成这些属性以保持它们的强类型?
Is there a better way to generate these properties that keeps them strongly typed?
推荐答案
更新: NotifyPropertyWeaver 已弃用并继续其作为 PropertyChanged.Fody.这是解决这个问题的绝对超酷的方法.这是一个仅编译时的解决方案.
UPDATE: NotifyPropertyWeaver is deprecated and continues its life as PropertyChanged.Fody. This is an absolute super cool way to solves this issue. It is a compile time only solution.
这里有一些可以为您节省代码和麻烦的东西:NotifyPropertyWeaver
Here's something that will save you code and trouble: NotifyPropertyWeaver
使用上述内容,您可以在没有任何 INotifyPropertyChanged
相关代码的情况下实现您的属性,并且构建步骤将为您处理接线.
Using the above, you can implement your properties without any INotifyPropertyChanged
related code, and a build step will handle the wiring up for you.
这是一个简单的项目包含(也可通过 Nuget 获得),它将自动将 OnPropertyChanged
回调注入到任何实现 INotifyPropertyChanged
的类的属性中.它在编译时完成(因此没有运行时命中)并且您的代码可以只具有自动实现的属性(除非在您的情况下,您使用单独的支持对象).
It's a simple project include (also available via Nuget) that will automatically inject the OnPropertyChanged
callbacks into the properties of any class that implements INotifyPropertyChanged
. It does it at compile time (so no runtime hit) and your code can just have auto-implemented properties (except in your case, where you're using a separate backing object).
它甚至包括值相等检查,因此它涵盖了完整的逻辑.我还没有使用手动实现的属性对其进行测试,但值得一试.
It even includes the value equality check, so it covers the full logic. I haven't tested it with manually-implemented properties, but worth checking out.
我现在已经测试过了,它工作正常:手动实现的属性将正常工作".
I have tested it now, and it works fine: a manually implemented property will "just work."
这篇关于在wpf中快速生成ViewModel属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!