WPF multi-source binding and WPF source binding
The control is bound to multiple data sources, and ListBox is bound to a collection. each item is bound to two attributes of the object in the collection, and the binding is formatted.
<ListBox ItemsSource="{StaticResource MyData}" IsSynchronizedWithCurrentItem="True"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock> <TextBlock.Text> <MultiBinding StringFormat="{}{0} -- Now only {1:C}!"> <Binding Path="Description"/> <Binding Path="Price"/> </MultiBinding> </TextBlock.Text> </TextBlock> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
Custom value conversion for multi-source binding. The TextBlock control is bound to one of the NameListData sets. When an object in the set is selected, the two attributes of the object are converted to the display value from the custom converter, the two properties of the object are FirstName and LastName. The complete name is displayed in the control through the converter. This is similar to the preceding multi-source binding format, but the converter can accept parameters, so it is more flexible. Here, you can control the display sequence of FirstName and LastName through parameters.
<TextBlock Name="textBox1" DataContext="{StaticResource NameListData}"> <TextBlock.Text> <MultiBinding Converter="{StaticResource myNameConverter}" ConverterParameter="FormatNormal"> <Binding Path="FirstName"/> <Binding Path="LastName"/> </MultiBinding> </TextBlock.Text> </TextBlock>
The following is the implementation of the custom converter. This class must implement the interface IMultiValueConverter, where Convert Converts the data source to the control direction, while ConvertBack is the opposite:
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; } }