除了 Mario Binder 的回答,这里有一个这样的转换器的例子:
public class ListToColoredComboboxItemsConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is IEnumerable<Measurement> measurements)
{
var comboBoxItems = new List<ComboBoxItem>(measurements.Count());
foreach (var measurement in measurements)
{
var item = new ComboBoxItem();
item.Content = measurement;
if (!string.IsNullOrWhiteSpace(measurement.ErrorMessage))
item.Foreground = Brushes.Red;
comboBoxItems.Add(item);
}
return comboBoxItems;
}
return null;
}
public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
并且可能您还想将选定的项目转换回一个值:
public class ComboBoxItemToItemConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return value;
}
public object ConvertBack(object value, Type targetTypes, object parameter, CultureInfo culture)
{
if (value is ComboBoxItem comboBoxItem)
{
return comboBoxItem.Content;
}
return null;
}
}