编写MVVM样板代码的更好方法? [英] A better way to write MVVM boilerplate code?
问题描述
我最近发现自己编写了许多样板MVVM代码,并且想知道是否有一种花哨的方法可以解决所有这些问题?我已经使用了实现INotifyPropertyChanged
的ViewModelBase
类,但是并不能解决必须编写所有访问器代码等问题.也许通过编写执行此操作的自定义属性或通过模板系统来实现?
I have found myself recently writing a lot of boilerplate MVVM code and wonder if there is a fancy way to get around writing it all? I already use a ViewModelBase
class that implements INotifyPropertyChanged
but that doesnt solve the problem of having to write all the accessor code etc. Perhaps by writing a custom attribute that does this, or via a templating system?
public MyClass : ViewModelBase
{
private int someVariable;
public int SomeVariable
{
get
{
return this.someVariable;
}
set
{
this.someVariable = value;
this.NotifyPropertyChanged("SomeVariable");
}
}
}
推荐答案
我有一个代码段,可用于创建视图模型属性.这个特定的代码段使用了其他评论者所暗示的Expression<Func<T>>
表示法.
I have a snippet that i use to create my view model properties. This particular snippet uses the Expression<Func<T>>
notation that other commenters have hinted upon.
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
<Title>View Model Property</Title>
<Description>
Declares a property and member suitable for Viewmodel implementation.
</Description>
<HelpUrl>
</HelpUrl>
<Shortcut>propvm</Shortcut>
</Header>
<Snippet>
<Declarations>
<Literal Editable="true">
<ID>propname</ID>
<ToolTip>Property Name</ToolTip>
<Default>Name</Default>
<Function>
</Function>
</Literal>
<Literal Editable="true">
<ID>type</ID>
<ToolTip>Property type.</ToolTip>
<Default>Type</Default>
<Function>
</Function>
</Literal>
<Literal Editable="true">
<ID>init</ID>
<ToolTip>Member initialisation</ToolTip>
<Default>null</Default>
<Function>
</Function>
</Literal>
</Declarations>
<Code Language="csharp" Kind="type decl"><![CDATA[public $type$ $propname$
{
get { return m_$propname$; }
set
{
m_$propname$ = value;
base.OnPropertyChanged(() => $propname$);
}
} $type$ m_$propname$ = default($type$);$end$]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
注意对base.PropertyChanged()
的呼叫.我有一个ViewModelBase
类来为我做繁重的属性通知和验证.
Note the call to base.PropertyChanged()
. I have a ViewModelBase
class to do the heavy lifting of property notification and validation for me.
用法是这样
- 键入
propvm
- 打 TAB 两次
- 填写突出显示的字段,然后按Tab键翻到下一个!
- Type
propvm
- Hit TAB twice
- Fill in the highlighted field and press tab to flip to the next one!
这篇关于编写MVVM样板代码的更好方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!