WPF
IValueConverter 데이터 변환
스티커
2009. 5. 28. 15:45
// Custom class implements the IValueConverter interface. public class DateToStringConverter : IValueConverter { #region IValueConverter Members // Define the Convert method to change a DateTime object to a month string. public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { // value is the data from the source object. DateTime thisdate = (DateTime)value; int monthnum = thisdate.Month; string month; switch (monthnum) { case 1: month = "January"; break; case 2: month = "February"; break; default: month = "Month not found"; break; } // Return the value to pass to the target. return month; } // ConvertBack is not implemented for a OneWay binding. public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } #endregion }
사용법
- <Grid.Resources>
- <DataTemplate x:Name="dataTemplate">
- <Grid>
- <Grid.ColumnDefinitions>
- <ColumnDefinition />
- <ColumnDefinition />
- </Grid.ColumnDefinitions>
- <TextBlock Grid.Column="0" Text="{Binding Month, Converter={StaticResource Converter1}}"/>
- <TextBlock Grid.Column="1" Text="{Binding Total}"/>
- </Grid>
- </DataTemplate>
- </Grid.Resources>
- <ItemsControl x:Name="IC1" ItemsSource="{Binding}" ItemTemplate="{StaticResource dataTemplate}"/>