用于ObservableCollection的WPF转换器与静态项结合使用

时间:2015-07-29 15:41:33

标签: .net wpf observablecollection ivalueconverter

我正在尝试将ComboBox绑定到ObservableCollection,其中包含一些静态项目作为第一项,然后是集合中的实际项目。

No index
1% p.a.
5% p.a.
--------
Item1
Item2
Item3

我认为绑定转换器可以解决问题。

<ComboBox ItemsSource = "{Binding indexes}, Converter={StaticResource IndexCollectionConverter}}" />

在运行时添加和删除项目的集合。

public virtual ObservableCollection<indexation> indexes{ get; set; }

我需要总是有一些静态项目(前3项),然后是分隔符(如果可能,可选但很好),然后是实际ObservableCollection中的所有项目。

我知道CompositeCollection类,但在XAML中实现时,Visual Studio输出窗口给出了绑定错误。

所以我尝试了转换器但是我迷失了如何从convert方法返回这种集合。

public class IndexCollectionConverter: IValueConverter {

    public object Convert(object value, Type targetType, object parameter, Globalization.CultureInfo culture)
    {
        //LOST HERE...
    }

    public object ConvertBack(object value, Type targetType, object parameter, Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

如何定义转换器以返回集合?

1 个答案:

答案 0 :(得分:0)

尝试IMultiValueConverter:

Fragment

以下是一些示例代码,我正在使用XmlDataProviders来显示它的工作情况,但您可以将源代码绑定更改为任何代码:

public class IndexCollectionConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return values                               // loop through all values
            .Select(v => v as IEnumerable<object>)  // cast to something we can enumerate
            .Where(v => v != null)                  // ignore anything we can't
            .SelectMany(v => v)                     // concat them all into a single list
            .ToList();                              // turn into a memory array now
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

结果: