在使用 Silverlight 对绑定数据进行展现的时候(如 ListBox、DataGrid),经常需要对数据的表现形式进行各式各样的处理,silverlight提供了一个System.Windows.Data.IValueConverter接口,它提供两个方法 Convert和ConvertBack 前者是资源到目标元素时转换 后者是目标到资源时转换。
下面根据几种需求,来说明一下IValueConverter的使用方式。
1.在DataGrid中的数据,我需要大于0的数据是红色,小于0的是绿色,等于0的是白色。OK,针对这种需求,那么,首先我们先创建一个类型
public class QuotaChangePriceConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
decimal price;
bool success = decimal.TryParse(value.ToString(), out price);
if (!success)
{
return value;
}
if (price > 0)
{
return Application.Current.Resources["Heading5FontBrush"] as SolidColorBrush;
}
else if (price < 0)
{
return Application.Current.Resources["Heading4FontBrush"] as SolidColorBrush;
}
else
{
return Application.Current.Resources["GrdRowTextBrush"] as SolidColorBrush;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
然后xaml代码中,首先在 XAML 中注册空间命名并声明:例如
<UserControl x:Class="GreenFutures.SLClient.Views.Controls.Quota"
xmlns:local="clr-namespace:GreenFutures.SLClient.Views.Controls">
<UserControl.Resources>
<local:QuotaChangePriceConverter x:Key="covChangePrice" />
</UserControl.Resources>
然后再控件中进行绑定调用
<sdk:DataGridTemplateColumn Header="开盘价" SortMemberPath="OpenPrice">
<sdk:DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<Grid>
<TextBlock Text="{Binding OpenPrice, Mode=OneWay, StringFormat=\{0:F1\}}"
Foreground="{Binding Path=PriceDifference, Converter={StaticResource covChangePrice}}"
HorizontalAlignment="Right"
VerticalAlignment="Center"
Margin="15,0,5,0" />
</Grid>
</DataTemplate>
</sdk:DataGridTemplateColumn.CellTemplate>
</sdk:DataGridTemplateColumn>
2.对绑定的数据进行格式化处理,比如对字符串的处理,时间格式的处理,数据展现形式的处理(大于或小于0的数据正常显示,等于0的要显示成‘-’)等等需求,针对字符串HTML标签过滤举例:
public class HTMLElementConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if (value.ToString() == "")
{
value = "请点击“查看详情”按钮,进入网站下载浏览。";
}
string context = value.ToString();
context = context.Replace(" ", ""); //空格
context = Regex.Replace(context, @"<[^>]*", "");//用Regex的replace 先将<str </str 给过滤掉
context = context.Replace(">", "");//再用字符串的replace给 >>过滤掉
return context.Trim();
//return System.Text.RegularExpressions.Regex.Replace(context, "<[^>]+>", "");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
OK,xaml中的使用和上方讲解一样,代码为:
<UserControl x:Class="GreenFutures.SLClient.Views.Controls.AlternativeAccordion"
xmlns:local="clr-namespace:GreenFutures.SLClient.Views.Controls">
<UserControl.Resources>
<local:HTMLElementConverter x:Key="HTMLConverter" />
</UserControl.Resources>
<TextBlock Margin="0"
TextWrapping="Wrap"
Text="{Binding Summary.Text,Converter={StaticResource HTMLConverter}}" />