A contestant in the BALL Watch Silverlight Contest was working on creating his entry (Due August 5, 2010) and sent me a question on data binding to the day of the week. The watch that he is creating displays the day abbreviated and capitalized and he wanted to use data binding like I showed in this tutorial. Since the Chronograph control exposes a DateTime Date property, he could bind to that and use Date.DayOfWeek property, but that would return values like Monday and Tuesday, not MON and TUE. The solution in this case is to create a value converter and use that in the binding.
I create value converters so often in my Silverlight and WPF development, that I created a C# item template that I use over and over in Visual Studio. I’ve posted the item template to the Visual Studio Gallery so you can use it too. The Visual Studio Gallery is integrated with Visual Studio 2010, so you can install and start using the template right from Visual Studio:
If you want to create your own project or item templates for Visual Studio 2010 and share them like this on the Visual Studio Gallery, you should first download and install the Visual Studio SDK and then create a VSIX Project from Visual Studio with the item template .zip its contents.
<TextBlock Text="{Binding Date, Converter={StaticResource DayOfWeekConverter1}, RelativeSource={RelativeSource TemplatedParent}}"/>
namespace SilverlightApplication6 { using System; using System.Windows; using System.Windows.Data; /// <summary> /// Value Converter for converting DateTime to 3-letter capitalized abbreviations /// </summary> public class DayOfWeekConverter : IValueConverter { #region IValueConverter Members /// <summary> /// Convert a DayOfWeek to a 3-letter capitalized abbreviation (MON, TUE, WED, THU, FRI, SAT, SUN) /// </summary> /// <param name="value">a DateTime</param> /// <param name="targetType">the target type to convert to</param> /// <param name="parameter">an unused parameter</param> /// <param name="culture">an unused culture</param> /// <returns>null or the 3-letter capitalized abbreviation</returns> public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { if (value == null) { return null; } var date = (DateTime)value; var dayOfWeek = date.DayOfWeek; var abbreviated = dayOfWeek.ToString().ToUpperInvariant().Substring(0, 3); return abbreviated; } /// <summary> /// Not Supported conversion /// </summary> /// <param name="value">the value to convert back</param> /// <param name="targetType">the target type</param> /// <param name="parameter">the parameter</param> /// <param name="culture">the culture</param> /// <returns> a <see cref="DependencyProperty.UnsetValue"/></returns> public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { return DependencyProperty.UnsetValue; } #endregion } }