Random programming things I'd want to remember

Saturday, March 22, 2014

Code snippet for MVVM command in a ViewModel

Since code snippets are not that hard to do, here is another one. This one gets all the plumbing for a command in a ViewModel, I used DelegateCommand class to abstract all the INotifyPropertyChanged functionality. See my other posts on the subject. Call this one in VisualStudio by its shortcut, dcmvvm.
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets
    xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <CodeSnippet Format="1.0.0">
    <Header>
      <Title>Plumbing for an MVVM DelegateCommand</Title>
      <Author>yevgeller</Author>
      <Description>Plumbing for an MVVM DelegateCommand for use in a ViewModel</Description>
      <Shortcut>dcmvvm</Shortcut>
    </Header>
    <Snippet>
      <Declarations>
        <Literal>
          <ID>cmd1</ID>
          <ToolTip>Prefix for a private variable that holds command name.</ToolTip>
          <Default>your</Default>
        </Literal>
        <Literal>
          <ID>cmd2</ID>
          <ToolTip>Prefix for a property Name that exposes the command to the View.</ToolTip>
          <Default>Your</Default>
        </Literal>
      </Declarations>
      <Code Language="csharp">
        <![CDATA[
        DelegateCommand _$cmd1$Command;
        public ICommand $cmd2$Command { get { return _$cmd1$Command; } }
        private void $cmd2$CommandAction(object obj)
        {
            throw new NotImplementedException();
        }
        //add the following line to ViewModel constructor or wherever else you initialize your commands:
        _$cmd1$Command = new DelegateCommand(this.$cmd2$CommandAction, this.Can$cmd2$);
        private bool Can$cmd2$(object obj)
        {
            return true;
        }
      ]]>
      </Code>
    </Snippet>
  </CodeSnippet>
</CodeSnippets>

No comments: