除了将单个不同类型的数据转换类型,使它与target的数据类型匹配外,有时我们需要muti binding,它可以将一个target property绑定source object的多个不同属性,然后通过实现IMultiValueConverter接口,根据不同的逻辑来决定target property要显示什么。
如下,首先有一个Data object类:
public class MyData
{
public MyData()
{
}
private string _firstName;
private string _lastName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
然后是xaml文件:
<Window x:Class="WpfApplication32.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:WpfApplication32"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<c:MyData x:Key="myData" FirstName="xiong" LastName="bear"></c:MyData>
<c:NameConverter x:Key="myNameConverter"/>
</Window.Resources>
<Grid>
<TextBlock Width="140" Height="50" Name="myText">
<TextBlock.DataContext>
<Binding Source="{StaticResource myData}"></Binding>
</TextBlock.DataContext>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource myNameConverter}"
ConverterParameter="FormatLastFirst">
<Binding Path="FirstName"/>
<Binding Path="LastName"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Grid>
</Window>
接下来是Converter类:
public class NameConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
string name;
switch ((string)parameter)
{
case "FormatLastFirst":
name = values[1] + ", " + values[0];
break;
case "FormatNormal":
default:
name = values[0] + " " + values[1];
break;
}
return name;
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
{
string[] splitValues = ((string)value).Split(' ');
return splitValues;
}
}
这样当指定不同的ConverterParameter时,就可以根据需要组合不同的显示值了。