尝试使用IValueConverter
例子:
xml:
<Window x:Class="ConverterSpike.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ConverterSpike="clr-namespace:ConverterSpike"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<ConverterSpike:DateStringConverter x:Key="DateConverter" />
</Window.Resources>
<Grid>
<TextBlock Text="{Binding MyProperty, Converter={StaticResource DateConverter}}" />
</Grid>
</Window>
转换器:
using System;
using System.Globalization;
using System.Windows.Data;
namespace ConverterSpike
{
public class DateStringConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null) return string.Empty;
var date = value as string;
if (string.IsNullOrWhiteSpace(date)) return string.Empty;
var formattedString = string.Empty; //Convert to DateTime, Check past or furture date, apply string format
return formattedString;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}