partial class DaveKehring : IProgrammer { }  RSS 2.0
# Sunday, February 01, 2009

Code snippets in Visual Studio are very helpful when you have to type the same old code structure again and again. I found myself doing this on a recent project and decided to create a code snippet for it. I'm using Microsofts Composite Application Guidance (a.k.a. Prism) and the Model-View-ViewModel pattern (M-V-VM). My ViewModels implement commands that are hooked into from the Xaml View. The command type is DelegateCommand<T>, a class provided by the Composite WPF library that comes with Prism. Here's my snippet:

<?xml version="1.0" encoding="utf-8"?>

<CodeSnippets xmlns="">

  <CodeSnippet Format="1.0.0">




      <Author>Dave Kehring</Author>

      <Description>Creates a Prism DelegateCommand.</Description>














          <ToolTip>Parameter type</ToolTip>





          <ToolTip>Command name</ToolTip>




      <Code Language="csharp">


        DelegateCommand<$type$> _$name$Command;

        public DelegateCommand<$type$> $name$Command




                if (_$name$Command == null)

                    _$name$Command = new DelegateCommand<$type$>($name$, Can$name$);

                return _$name$Command;




        public bool Can$name$($type$ param)




        public void $name$($type$ param)









This produces the following example property declaration:

        DelegateCommand<object> _SaveCommand;
        public DelegateCommand<object> SaveCommand
                if (_SaveCommand == null)
                    _SaveCommand = new DelegateCommand<object>(Save, CanSave);
                return _SaveCommand;
        public bool CanSave(object param)
        public void Save(object param)

The code snippet creates a private DelegateCommand member and a standard property declaration with only a getter. The command is lazy-initialized. The two methods stubs are called by the DelegateCommand during runtime execution.

To use this snippet, save it in a file with the .snippet extension into %\My Documents\Visual Studio 2008\Snippets\Visual C#\My Code Snippets. Then, in Visual Studio, you simply type "delcom" to run the snippet:

Hit Tab to insert the snippet code into the IDE. Then, you provide replacement values for the DelegateCommand's type value (this is the type of the parameter passed to the command methods) and the name of the command:


Sunday, February 01, 2009 10:41:42 AM (Eastern Standard Time, UTC-05:00)  #    Comments [0] -
Visual Studio
<February 2009>
About the author/Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.

© Copyright 2014
Dave Kehring
Sign In
Total Posts: 11
This Year: 0
This Month: 0
This Week: 0
Comments: 2
Pick a theme:
All Content © 2014, Dave Kehring
DasBlog theme 'Business' created by Christoph De Baene (delarou)