Distinct Values in WPF Combobox

后端 未结 3 1984
时光取名叫无心
时光取名叫无心 2020-12-21 07:33

I would like to get distinct values in my databound combo box

as an example the values it has are: blue, blue, yellow, red, orange

I would like it to just di

相关标签:
3条回答
  • 2020-12-21 07:51

    Let's say your you have a List<String> values = blue, blue, yellow, red, orange

    you can do

    ComboBox.ItemsSource = values.Distinct();
    

    or if you are going for MVVM approach you can create a property and bind combo box itemssource with a property like

    public List<string> values
    {
        get
        {
        return value.Distinct();
         }
    }
    
    0 讨论(0)
  • 2020-12-21 08:02

    You could create an IValueConverter that converts your list into a distinct list:

    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();
        }
    }
    

    add this to resources:

    <local:DistinctConverter x:Key="distinctConverter" />
    

    and use it like this:

    <ComboBox ItemsSource="{Binding Vals, Converter={StaticResource distinctConverter}}" />
    
    0 讨论(0)
  • 2020-12-21 08:03

    if you are using WPF c# 4.0

    List<object> list = new List<object>();
            foreach (object o in myComboBox.Items)
                {
                if (!list.Contains(o))
                    {
                    list.Add(o);
                    }
                }
            myComboBox.Items.Clear();
            myComboBox.ItemsSource=list.ToArray();
    
    0 讨论(0)
提交回复
热议问题