WPF中的Converter
Converter可以是在WPF开发过程中经常用到的一个组件,Converter究竟是什么呢?简单的说,Converter给我们提供了一个绑定源到目的过程中的一个转换器。最常见的用途就是,当我们将元数据绑定到用户界面时,因为不能将元数据直接显示到用户界面,我们要将该数据转换成您想要输出的数据显示到用户界面中。
接下来,我们用一个例子说明Converter是如何实现的。这个例子是,我们在元数据中定义1,2,3,显示到界面中确是,红、黄、兰。
ColorConverter.cs
[ValueConversion(typeof(int), typeof(Brush))]
public class ColorConverter : IValueConverter
{
//数据转换的方法
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
int index = (int)value;
Brush result = null;
switch (index)
{
case 1:
result = new SolidColorBrush(Colors.Red);
break;
case 2:
result = new SolidColorBrush(Colors.Yellow);
break;
case 3:
result = new SolidColorBrush(Colors.Blue);
break;
}
return result;
}
//双向绑定时,Convert方法的反向实现
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return null;
}
}
这里就是Converter的一个实现,只需要继承IValueConverter接口,并实现成员方法。
MainWindow.xaml.cs
public partial class MainWindow : Window
{
private List<int> _ListData = new List<int>() { 1, 2, 3 };
public List<int> ListData
{
get { return this._ListData; }
}
public MainWindow()
{
InitializeComponent();
}
}
这里定义了一个int型的集合,由前台代码进行绑定
MainWindow.xaml
<Window x:Class="ConverterDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ConverterDemo"
Title="MainWindow" Height="350" Width="525" x:Name="mainWindow">
<Window.Resources>
<local:ColorConverter x:Key="converterColor"/>
</Window.Resources>
<Grid>
<ListView x:Name="lstBox" ItemsSource="{Binding ElementName=mainWindow,Path=ListData}">
<ListView.ItemTemplate>
<DataTemplate>
<TextBlock FontSize="20" FontWeight="Bold" Text="{Binding}"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
这里我们暂时不使用Converter看看显示效果
MainWindow.xaml
<Window x:Class="ConverterDemo.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ConverterDemo"
Title="MainWindow" Height="350" Width="525" x:Name="mainWindow">
<Window.Resources>
<local:ColorConverter x:Key="converterColor"/>
</Window.Resources>
<Grid>
<ListView x:Name="lstBox" ItemsSource="{Binding ElementName=mainWindow,Path=ListData}">
<ListView.ItemTemplate>
<DataTemplate>
<Border Background="{Binding Converter={StaticResource converterColor}}" Width="300" Height="30">
<TextBlock FontSize="20" FontWeight="Bold" Text="{Binding}"/>
</Border>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Grid>
</Window>
这里,我们先在xaml文档Resource中声明这个Converter,再加入一个Border,并且和它的背景颜色进行绑定,我们看一下效果:
是不是很简单?我们可以通过Converter实现各种类型的转换,如输出数据表格的时候,实际数据是一些枚举值,而显示出来的是我们真正要显示的值。
原创文章,转载请注明: 转载自.NET开发者
本文链接地址: WPF中的Converter
Related posts:


Converter这个工具好像很好用哦~
高手!