We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
As you all remember in my article about Custom WPF Context Menu I mentioned that my WPF Binding Converter was a singleton, and I promised to tell you why, so here comes the 3 ways I know of using WPF Binding Converters. We will start from the worst (in my opinion) and move on the the best.
To start off here is the Binding Converter:
This is the most simple way of using WPF converters, create you Converter Class and link to it as a StaticResource. Here is the code:
This is very easy and simple but there is one drawback to it which I hope the WPF team will fix someday. It appears that every time there is a need to use the converter the Application will create a new Converter class, use it and then dispose it. If you have a heavy application with allot of binding and converters this could be costly. I am not 100% sure that it is true but I did allot of checking and the performance is slower. So lets move on to the next way.
Here we will not allow WPF to create and dispose the Converters all the time be creating a Static Class that will hold all the Converters in one place something like this:
You can add as may converters as you want to this class. It is sort of a Converters repository. Here is the code for using the converter:
Ok, lets take a break.
The first example is simple but costly. the second one is better in performance but requires maintaining a Converters class. If only we could get rid of maintaining the Converters Class… We Can!!!
This method will allow us to enjoy both worlds. First we will need to add a singleton implementation to the Converter ( I know it is not thread safe and all…):
And the Usage is similar to the second example:
No you don’t have to maintain a converter class. I think this is the best method for using Converters. I made myself a template for a converter that already has the singleton implementation so creating a new one is easy.
Subscribe to our feed and get the complete code sample for this article.
Don’t forget to check out the Context Menu article where it all started
Need help or know of a different way of using Converters? Let me know
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd