有时我们展现的数据,需要进行转换,比如如果一个学生的成绩过了60,我们显示一个Pass的图片。
XAML:
01 |
< Window x:Class = "DeepXAML.MainWindow" |
04 |
xmlns:local = "clr-namespace:DeepXAML" |
05 |
xmlns:sys = "clr-namespace:System;assembly=mscorlib" |
06 |
Title = "MainWindow" Height = "250" Width = "450" > |
08 |
< local:ScoreToImageConverter x:Key = "sti" ></ local:ScoreToImageConverter > |
11 |
< ListBox x:Name = "listBoxStudents" Margin = "10" > |
12 |
< ListBox.ItemTemplate > |
14 |
< StackPanel Orientation = "Horizontal" > |
15 |
< TextBlock Text = "{Binding Path=Name}" ></ TextBlock > |
16 |
< Image Source = "{Binding Path=Score,Converter={StaticResource sti}}" Height = "20" ></ Image > |
19 |
</ ListBox.ItemTemplate > |
后台代码:
02 |
using System.Collections.Generic; |
04 |
using System.Windows.Data; |
05 |
using System.Windows.Documents; |
09 |
public partial class MainWindow : Window |
13 |
InitializeComponent(); |
14 |
List<Student> students = new List<Student>{ |
15 |
new Student{ Name= "Jack" , Score=90}, |
16 |
new Student{Name= "Tom" , Score=30}, |
17 |
new Student{ Name= "David" , Score=80} |
19 |
this .listBoxStudents.ItemsSource = students; |
25 |
public string Name { get ; set ; } |
26 |
public double Score { get ; set ; } |
28 |
public class ScoreToImageConverter : IValueConverter |
30 |
public object Convert( object value, Type targetType, object parameter, |
31 |
System.Globalization.CultureInfo culture) |
33 |
double score = ( double )value; |
35 |
return score >= 60 ? @"\images\pass.gif" : @"\images\nopass.gif" ; |
38 |
public object ConvertBack( object value, Type targetType, object parameter, |
39 |
System.Globalization.CultureInfo culture) |
41 |
throw new NotImplementedException(); |
运行结果