WPF Combobox中的独特值

San*_*sal 3 c# silverlight wpf combobox distinct

我想在我的数据绑定组合框中获得不同的值

例如,它具有的值是:蓝色,蓝色,黄色,红色,橙色

我希望它只显示一次蓝色.

我的主要想法是将所有组合框值都放入一个数组中,将数组设置为distinct,然后重新填充组合框.还有其他方法吗?

如果不是,我将如何从组合框中获取所有值?

谢谢

编辑 - 班级:

public class DistinctConverter : IValueConverter
{

}
Run Code Online (Sandbox Code Playgroud)

编辑 - 调试:

在此输入图像描述

svi*_*ick 9

您可以创建一个IValueConverter将列表转换为不同列表的列表:

public class DistinctConverter : IValueConverter
{
    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        var values = value as IEnumerable;
        if (values == null)
            return null;
        return values.Cast<object>().Distinct();
    }

    public object ConvertBack(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

将此添加到资源:

<local:DistinctConverter x:Key="distinctConverter" />
Run Code Online (Sandbox Code Playgroud)

并像这样使用它:

<ComboBox ItemsSource="{Binding Vals, Converter={StaticResource distinctConverter}}" />
Run Code Online (Sandbox Code Playgroud)