Click here to Skip to main content
15,885,537 members
Articles / Desktop Programming / WPF

A Simple Tool to Generate C# Code for Properties and DependencyProperties

Rate me:
Please Sign up or sign in to vote.
2.12/5 (7 votes)
30 Apr 2018CPOL3 min read 11.8K   218   8   6
A simple tool to generate C# code for Properties and DependencyProperties

Introduction

For WPF applications, properties play a key role in connecting the user interface to code. The number of properties may be significant for complex applications. For proper binding, you also may want to implement the INotifyPropertyChanged interface. This results into a significant amount of code for each Property, where information must be typed multiple times. An example is shown below:

C#
private String _PropertyType = String.Empty;
public String PropertyType
{
get { return _PropertyType; }
set
  {
  _PropertyType = value;
  OnPropertyChanged("PropertyType");
  }
}

In the example, you see the text PropertyType occurs five times.

PropertyCreator is a stand-alone tool that makes it a lot easier to create large numbers of properties, generating the required C# code.

I recently created my first UserControl. For this control, I needed about 10 DependencyProperties, This even needs more code to write.

Using the Code

In the project where you want to use the generated properties, you need to implement a class to support INotifyPropertyChanged. This class will make sure WPF is able to update the fields in the UI if you change a Property in the code behind. (This code comes from the book "Learn WPF MVVM" by Arnaud Weil). The nice thing is that together with PropertyCreator, this solves the issue, no need to implement it separately for each class.

C#
using System;
using System.ComponentModel;
 
namespace PropertyCreator
	{
	public class CNotifier : INotifyPropertyChanged
 
		{
		public event PropertyChangedEventHandler
			PropertyChanged;
 
		protected void OnPropertyChanged(String PropertyName)
			{
			PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
			}
		}
	}

I registered the tool as an external tool in Visual Studio, so you have it always nearby:

Image 1

Usage is easy, See the example below:

Image 2

For a DependencyProperty, check the approriate CheckBox:

Image 3

The Add button will wipe the PropertyName and insert an empty line in the TextBox. Code is copied to the clipboard each time you press the Create button. The Clear Entry button can be used to clear the entry fields. For DependencyProperties, it will not wipe the ControlClass name. The Clear button wipes all content, without further warning.

You may want to change the screen size a bit according to your taste. I made it small for the purpose of this article.

Points of Interest

Most of the code is straight forward, but the XAML code for the TextBox has few interesting details:

XML
<TextBox Name="ResultTextBox" Height="246" Margin="5"
	FontFamily="Courier New"
	ScrollViewer.VerticalScrollBarVisibility="Auto"
	ScrollViewer.HorizontalScrollBarVisibility="Auto"
	ScrollViewer.CanContentScroll="True"
	Text="{Binding PropertyCode, Mode=TwoWay, NotifyOnSourceUpdated=True}"
	TextWrapping="Wrap"/>

In order for the scrolling to work properly (it must know the height of the box), I set the Height Property explicitly. A TextBox normally updates text from the UI (Target), because I update mainly from the Source, the binding mode must be set as TwoWay. I also set an explicit notification if the Source is updated (I am not sure if this is really needed, let me know).

C#
private void OnCreatePropertyButtonClick(oject sender, RoutedEventArgs e)
		{
		if (Property.IsDependencyProperty)
			{
			Property.CreateDependencyProperty();
			}
		else
			{
			Property.CreateProperty();
			}
		ResultTextBox.ScrollToEnd();
		}

Because you normally like to see the last item added, after each update, we scroll to the end.

To do

I intended this application as a Minimum Viable Product. It works, but is a bit limited in scope. What may be done:

  • Make the naming of the CNotify class flexible and settable in the registry
  • Better integration with Visual Studio
  • Support other languages for code generation
  • Make a nicer user interface
  • ...

If you would like to contribute to this small project, please contact me.

History

  • 30th April, 2018: First public version
  • 30th April 2018: Fixed issue signing code
This article was originally posted at https://github.com/RudolfJan/PropertyCreator

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Retired
Netherlands Netherlands
Got an MS degree in Electrical Engineering a long time ago (in the time before Computer Science was invented as something you could study). I have been involved somehow in software development since I created my first Algol 60 program, using punched cards and an IBM360 machine. Now I develop C#/WPF desktop applications, partly for fun, partly to help other people.

Comments and Discussions

 
GeneralMy vote of 2 Pin
jackmos8-May-18 3:02
professionaljackmos8-May-18 3:02 
SuggestionUnnecessary event raising Pin
Luka2-May-18 5:14
Luka2-May-18 5:14 
QuestionHow is this better than a simple code snippet? Pin
netizenk30-Apr-18 6:19
professionalnetizenk30-Apr-18 6:19 
AnswerRe: How is this better than a simple code snippet? Pin
Rudolf Jan30-Apr-18 6:32
Rudolf Jan30-Apr-18 6:32 
QuestionError Compiling Pin
Kevin Marois30-Apr-18 5:41
professionalKevin Marois30-Apr-18 5:41 
AnswerRe: Error Compiling Pin
Rudolf Jan30-Apr-18 6:58
Rudolf Jan30-Apr-18 6:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.