我发现自己最近编写了很多样板 MVVM 代码,并且想知道是否有一种奇特的方法可以绕过编写所有这些代码?我已经使用了ViewModelBase
实现的类INotifyPropertyChanged
但这并不能解决必须编写所有访问器代码等的问题。也许通过编写一个自定义属性来执行此操作,或者通过模板系统?
public MyClass : ViewModelBase
{
private int someVariable;
public int SomeVariable
{
get
{
return this.someVariable;
}
set
{
this.someVariable = value;
this.NotifyPropertyChanged("SomeVariable");
}
}
}
我有一个用于创建视图模型属性的片段。这个特定的片段使用Expression<Func<T>>
其他评论者已经暗示的符号。
<?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
类为我完成属性通知和验证的繁重工作。
用法是这样的:
- Type
propvm
- Hit TAB twice
- 填写突出显示的字段,然后按 Tab 键翻到下一个!
演练:创建代码片段 http://msdn.microsoft.com/en-us/library/ms165394%28v=vs.110%29.aspx
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)