IValueConverter值转换器,可以将一种类型转换为另一种类型,比如将值类型转为字符串,将图片url转换为图片类型,也可以将一个值进行计算转换为新值等等。在WPF,一般在绑定的场合用的是比较多的。下面通过一个简单的例子看看IValueConverter的用法。
首先,我们看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);
比如以我们最常见的页码转换问题来看,一般进行分页时,都是从0开始的,但是显示是是要从第一页显示的。那么就可以使用转换器来完成。
继承IValueConverter接口:
public class PageIndexConvert:IValueConverter
{
public int AddValue { get; set; }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int curentvalue = ToInt(value);
curentvalue += AddValue;
return curentvalue;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int curentvalue = ToInt(value);
curentvalue -= AddValue;
return curentvalue;
}
public int ToInt(object value)
{
if (value == DBNull.Value || value == null || string.IsNullOrEmpty(value.ToString()))
{
return int.MinValue;
}
try
{
return System.Convert.ToInt32(value);
}
catch
{
return int.MinValue;
}
}
}
界面使用写好的转换器:
<Window x:Class="TestConvert.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestConvert"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Grid.Resources>
<!--引用转换器-->
<local:PageIndexConvert x:Key="addoneconvert" AddValue="1"/>
</Grid.Resources>
<TextBox Height="52" HorizontalAlignment="Left" Margin="179,118,0,0" Name="textBox1" VerticalAlignment="Top" Width="152" KeyDown="NumberTextBox_KeyDown" />
<!--使用转换器-->
<TextBlock Height="44" HorizontalAlignment="Left" Margin="181,202,0,0" Name="textBlock1"
Text="{Binding ElementName=textBox1, Path=Text,Converter={StaticResource addoneconvert}}"
VerticalAlignment="Top" Width="150" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="105,132,0,0" Name="textBlock2" Text="输 入:" VerticalAlignment="Top" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="105,202,0,0" Name="textBlock3" Text="转 换:" VerticalAlignment="Top" />
</Grid>
</Window>
效果图:输入数字后就转换为指定的数值。
代码下载:
http://download.csdn.net/detail/yysyangyangyangshan/5416169

