需求中经常有这样的问题,我输入的是一种数据类型,但是我在界面显示的完全不同的东西。这样就需要转换。当然我可以将数据读进来的时候就转换,但是如果我读进来的是一个对象,里面有好多东西,我得把它一一找出来进行转换,最麻烦的为了绑定,我得一个一个绑定,或者存回对象里面去然后统一绑定。为了方便,我会设置一个类专门用于转换,但是WPF已经提供了一个Convert方法,我们可以在里面写,然后绑定的时候直接绑定就行了。
比如我有一个学生类 Student.
public class Student
{
public string ID { get; set; }
public string Name { get; set; }
public string Sex { get; set; }
}
客户给出的数据是
new Student() { ID = "1", Name = "Peter", Sex = "0" },
new Student() { ID = "2", Name = "Tom", Sex = "1" },
new Student() { ID = "3", Name = "Ben", Sex = "0" }
可见,sex这一项不是男女,按要求,0代表男,1代表女。所以需要显示出来的是男女而不是0,1.
那么现在WPF界面设置一个listbox,他的ItemSource直接绑定stuList.
List<Student> stuList = new List<Student>()
{
new Student() { ID = "1", Name = "Peter", Sex = "0" },
new Student() { ID = "2", Name = "Tom", Sex = "1" },
new Student() { ID = "3", Name = "Ben", Sex = "0" }
};
this.listBoxStudent.ItemsSource = stuList;
为了使sex转换,需要写一个类。
public class SexConverter:IValueConverter
{
public object Convert (object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
string result = "";
string sex = (string)value;
if (sex == "0")
{
result = "男";
}
else if (sex == "1")
{
result = "女";
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); }
}
这是个模板 ,所有的转换的公式都得照这个写。
那么xaml里面也需要绑定相应的东西。
里面的公式是这么写的。
<Window x:Class="WpfApp1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WpfApp1"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Window.Resources>
<!--引用资源-->
<local:SexConverter x:Key="SexConverter"/>
<Style TargetType="ListBoxItem">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Text="{Binding ID}" Width="60"/>
<TextBlock Text="{Binding Name}" Width="120"/>
<TextBlock Text="{Binding Sex,Converter={StaticResource SexConverter}}" Width="60"/>
</StackPanel>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<StackPanel>
<ListBox x:Name="listBoxStudent" Margin="5,5,4.6,5" Height="188"/>
</StackPanel>
</Window>
具体的代码链接:
(https://pan.baidu.com/s/10tlKrUbBndRz-yHqi2BmtA)