XAML实例教程系列 - XAML传递参数到值转换类实例
【转】http://silverlightchina.net/html/windows8/study/2012/0628/17004.html
在Windows 8和Silverlight应用开发中,经常需要进行值转换,例如从Boolean转换到Windows.Visibility,或者从数字转换到字符。下例中演示如何在XAML中传递参数到值转换类。
继上一篇值类型转换器(Type Converter), 这篇将通过实例代码讲解一个XAML开发小技巧。
在Silverlight应用开发中,经常需要进行值转换,例如从Boolean转换到Windows.Visibility,或者从数字转换到字符。下例中演示如何在XAML中传递参数到值转换类。
定义简单数据成员类:
public class Book
{
public DateTime PublishDate { get; set; }
}
{
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 )...
}
{
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;
myBook.PublishDate = DateTime.Now;
Binding binding = new Binding( "PublishDate" );
binding.Source = myBook;
binding.Converter = new DateTimeConverter();
binding.ConverterParameter = true;