在Silverlight应用开发中,经常需要进行值转换,例如从Boolean转换到Windows.Visibility,或者从数字转换到字符。下例中演示如何在XAML中传递参数到值转换类。
定义简单数据成员类:
public class Book { public DateTime PublishDate { get; set; } }
定义值转换类: public class DateTimeConverter : System.Windows.Data.IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )... public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture )... }
在XAML中传递参数到值转换类,
<TextBlock Text="{Binding PublishDate, Converter={StaticResource DateTimeConverter}, ConverterParameter=true}"/>
在CS代码中,传递参数到值转换类,
Book myBook = new Book(); myBook.PublishDate = DateTime.Now; Binding binding = new Binding( "PublishDate" ); binding.Source = myBook; binding.Converter = new DateTimeConverter(); binding.ConverterParameter = true;