Using Value Converters
This column is pretty much exactly what we want, but there is a finishing touch missing. If you look at the text, it has an annoying 12:00:00 AM after each date. Since we only care about the date itself and not the time, let's reformat this string to the short date format that matches what is shown in the DatePicker.
Add a new class to your Silverlight project and name it "DateTimeConverter". Then add:
C#
using System.Windows.Data; using System.Globalization;
public class DateTimeConverter: IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { DateTime date = (DateTime)value; return date.ToShortDateString(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { string strValue = value.ToString(); DateTime resultDateTime; if (DateTime.TryParse(strValue, out resultDateTime)) { return resultDateTime; } return value; } }
If you look at the code, a converter is a class that implements IValueConverter and as part of that provides two methods:
Convert and ConvertBack. These two methods are where you can perform your custom logic, in this case parsing a DateTime
to and from a short date string format.
Now that you have your reusable converter class you can use it in data binding.
Back in your Page.xaml add a local xmlns. To do this add the following in the UserControl tag next to the other xmlns
declarations:
xmlns:local="clr-namespace:_____________"Where the _________ is the name of your Application. IntelliSense should provide the correct syntax as an option in
the dropdown. Next add the converter to your UserControl as a static resource.
<UserControl.Resources> <local:DateTimeConverter x:Key="DateConverter" /> </< span>UserControl.Resources>Finally use the converter in the TextBox's binding in the DataGridTemplateColumn.
<TextBlock Text="{Binding Birthday, Converter={StaticResource DateConverter}}" FontFamily="Trebuchet MS" FontSize="11" Margin="5,4,5,4"/>
'WPF' 카테고리의 다른 글
[MSDN]BindingSource와 INotifyPropertyChanged 인터페이스를 사용하여 변경 내용 알림 발생 (0) | 2010.04.07 |
---|---|
실버라이트로 windows mobile 7 프로그램 개발 (0) | 2010.03.17 |
태그삭제 Convert (0) | 2010.01.02 |
ObservableCollection<(Of <(T>)>) Class (0) | 2010.01.02 |
INotifyPropertyChanged (0) | 2010.01.02 |
DataGrid 템플릿 (0) | 2010.01.02 |
간단한 data grid 사용법 (0) | 2010.01.02 |
쿠키사용법 (0) | 2009.12.15 |
웹 페이지에 Silverlight 추가 (0) | 2009.12.15 |
간단하게 세션처럼 사용하기?! (0) | 2009.12.15 |