编写MVVM样板代码的更好方法是什么?

Chr*_*ris 7 c# silverlight wpf mvvm inotifypropertychanged

我发现自己最近编写了大量的样板MVVM代码,并想知道是否有一种奇特的方式可以解决所有问题?我已经使用了一个ViewModelBase实现INotifyPropertyChanged但没有解决必须编写所有访问器代码等问题的类.也许通过编写一个自定义属性来执行此操作,或通过模板系统?

public MyClass : ViewModelBase
{
    private int someVariable;

    public int SomeVariable
    {
        get
        {
            return this.someVariable;
        }

        set
        {
            this.someVariable = value;
            this.NotifyPropertyChanged("SomeVariable");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Gus*_*dor 5

我有一个片段,用于创建我的视图模型属性.这个特殊的片段使用了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>
Run Code Online (Sandbox Code Playgroud)

请注意拨打电话base.PropertyChanged().我有一个ViewModelBase班级来为我做繁重的财产通知和验证.

用法是这样的:

  1. 类型 propvm
  2. TAB两次
  3. 填写突出显示的字段,然后按Tab键翻转到下一个字段!

演练:创建代码段