Freigeben über


Tip: creating your own snippets

I recently showed how to use the "Define a Dependency Property" snippet in VS to save time/frustration creating a new property on your control. I often need a property changed event as well, and it's a bit of a pain to go back and add it. I just figured out how to add/update snippets and thought I'd show you how to create a snippet with a property changed event:

 

        public int MyProperty {

            get { return (int)GetValue(MyPropertyProperty); }

            set { SetValue(MyPropertyProperty, value); }

        }

        // Using a DependencyProperty as the backing store for MyProperty. This enables animation, styling, binding, etc...

        public static readonly DependencyProperty MyPropertyProperty =

            DependencyProperty.Register("MyProperty", typeof(int), typeof(Window1), new UIPropertyMetadata(0, OnMyPropertyChanged));

        private static void OnMyPropertyChanged(DependencyObject dobj, DependencyPropertyChangedEventArgs e) {

            Window1 owner = dobj as Window1;

            if (owner != null) {

  // todo: execute property changed code.

            }

        }

If you have a spare few minutes, it is very easy to add this – you need to use the Code Snippet Manager.

 

Save this snippet to your disk as somefile.snippet (view source)
In VS 2008, open Tools > Code Snippets Manager
Choose the language (this is a C# snippet)
Choose import...
Find the .snippet file, import it, and voila!

Comments

  • Anonymous
    September 17, 2009
    Snippets are great. The Code Snippet Manager on the other hand is confusing and I prefer to just drop my snippet into the correct directory. eg. [Documents][VS Version]Code SnippetsVisual C#My Code Snippets