Sandeep Bansal
Sandeep Bansal

Reputation: 6394

Distinct Values in WPF Combobox

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 display blue once.

My main thought was to get all combo box values into an array, set the array as distinct and then re-populate the combo box. Is there any other way?

If not how would I actually get all the values from the combo box?

Thanks

EDIT -- Class:

public class DistinctConverter : IValueConverter
{

}

EDIT -- Debug:

enter image description here

Upvotes: 3

Views: 7438

Answers (3)

KMP
KMP

Reputation: 1

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

Upvotes: 0

svick
svick

Reputation: 244767

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}}" />

Upvotes: 9

Haris Hasan
Haris Hasan

Reputation: 30097

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

Upvotes: 1

Related Questions