案例地址:GitHub - microsoft/WPF-Samples: Repository for WPF related samples
一、运行界面
二、案例功能描述
实现类型转换器
三、分析代码
1、实现自定义类型转换器
public class MyConverter : IValueConverter
{
public object Convert(object o, Type type,
object parameter, CultureInfo culture)
{
var date = (DateTime) o;
switch (type.Name)
{
case "String":
return date.ToString("F", culture);
case "Brush":
return Brushes.Red;
default:
return o;
}
}
public object ConvertBack(object o, Type type,
object parameter, CultureInfo culture) => null;
}
2、使用类型转换器
<local:MyConverter x:Key="MyConverterReference"/>
<TextBlock Name="myconvertedtext"
Foreground="{Binding Path=TheDate,
Converter={StaticResource MyConverterReference}}">
<TextBlock.Text>
<Binding Path="TheDate"
Converter="{StaticResource MyConverterReference}"/>
</TextBlock.Text>
</TextBlock>