属性 - 如何避免重复的代码 [英] Properties - how to avoid code repetition
问题描述
在创建将在视图模型被用于遵循MVVM模式的应用类,我要实现的属性是这样的:
When creating a class that will be used in a viewmodel for an application that follows the MVVM pattern, I have to implement properties this way:
private string _MyStringPropertyA;
public string MyStringPropertyA
{
get {return _MyStringPropertyA;}
set
{
_MyStringPropertyA=value;
OnPropertyChanged(()=>MyStringPropertyA);
}
}
private string _MyStringPropertyB;
public string MyStringPropertyB
{
get {return _MyStringPropertyB;}
set
{
_MyStringPropertyB=value;
OnPropertyChanged(()=>MyStringPropertyB);
}
}
而不是更简单
instead of the more simple
public string MyStringPropertyA {get;set;}
public string MyStringPropertyA {get;set;}
只是因为我必须提高对二传手的事件。除了使我的代码越长,我认为它有复制和粘贴程序的代码味道。我能做些什么来避免这种情况?是否有可能建立一个泛型类的样子,我不知道, MVVMEnabled< T>
,我可以实现为:
simply because I have to raise the event on the setter. Besides making my code longer, I think it has a code smell of copy-and-paste programming. What can I do to avoid this? Is it possible to construct a generic class like, I don't know, MVVMEnabled<T>
which I can implement as:
public MVVMEnabled<string> MyStringPropertyA {get;set;}
public MVVMEnabled<string> MyStringPropertyB {get;set;}
,以便在通用类中的代码将确保OnPropertyChanged火灾当值设置?
so that the code in the generic class will ensure that the OnPropertyChanged fires when value is set?
推荐答案
我在哪里工作,我们做同样的东西你的 MVVMEnabled
建议,效果很好。
Where I work we do something similar to your MVVMEnabled
suggestion and it works well.
要观看的唯一一件事是,在 MVVMEnabled
的属性的属性的值现在藏(值,例如),所以你最终获得一个稍微详细绑定表达式,如 {结合MyStringPropertyA.Value}
The only thing to watch for is that the value of the property is now tucked away in a property of MVVMEnabled
(value, for example), so you end up with a slightly more verbose binding expression, such as {Binding MyStringPropertyA.Value}
要做到这一点有 MVVMEnabled
实现INotifyPropertyChanged。你需要的属性,比如值
这是将(在您的示例字符串)进行管理的值:
To do this have MVVMEnabled
implement INotifyPropertyChanged. You'll need a property, say Value
which is the value that will be managed (a string in your example):
public T Value
{
get{return m_Value;}
set
{
if(m_Value != value)
{
m_Value = value;
OnPropertyChanged(()=>Value);
}
}
}
在主类让你属性只读:
public MVVMEnabled<string> MyStringPropertyA {get;private set;}
和在构造函数初始化:
public SomeModel()
{
this.MyStringPropertyA = new MVVMEnabled<string>();
}
它是只读的原因是因为你改变通过价值值
属性,永不 MVVMEnabled
属性。
现在当你需要改变它做这样的事情:
Now, when you need to change it do something like this:
this.MyStringPropertyA.Value = "hello, world";
和只要你的绑定是这样的:
And as long as your binding is this:
{Binding MyStringPropertyA.Value}
您应该ok了。
这篇关于属性 - 如何避免重复的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!