The other day I was working on a WPF functionality that requires me to format a user input from a DatePickerTextBox. I needed to take the input, parse it into DateTime and format the output based on a display format specified by the user.
I thought this should be straightforward. So I went ahead and implemented my solution using the following XAML code:
As a result, Visual Studio nicely greeted me with the following error message on line 12:
A ‘Binding’ cannot be set on the ‘ConverterParameter’ property of type ‘Binding’. A ‘Binding’ can only be set on a DependencyProperty of a DependencyObject.
Just a background as to why this was required. The customer requirement wants us to implement a datetime control in WPF that is a textbox without using the traditional DateTime picker provided in WPF. The traditional DateTime picker will usually pop-up with a window that allows you to pick a date and time. The challenge with the picker is it doesn’t allow for much customization in the way of how you want your user to input the values and limits the display format to a number of options.
This new datetime picker solves that problem by allowing custom formatting for various user inputs. For example, you could type in “MM/dd/yy”, “MMddyy” or “dd/MM/yyyy” and so on and so forth.
Back to the issue of being able to format the user input. The error is being caused because I was trying to bind to the ConverterParameter property. The way to rightly solve this, considering other approaches such as attached properties, creating a special user control, dependency property, is using a multivalue converter. This approach gives us the benefit of leveraging passing in the value typed-in by the user and also to specify the display output format. For the purpose of this blog, the Format parameter is binded to a ViewModel property.
We do this by applying the code below:
With this implementation, we can conveniently pass-in a Format parameter that is binded to our ViewModel without getting screamed at by Visual Studio.
In essence, we leveraged the ability of Binding within a MultiBinding class with a IMultiValueConverter. As seen from the problem definition in the first few paragraphs, this would not have been possible by using a simple binding with a simple IValueConverter and a ConverterParameter property.
There you have it. Please let me know what you think of the article in the comment below. It helps with feedback and better content for you guys next time.
Leave a Reply