Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 255
Sandeep Bansal Avatar asked Mar 02 '26 05:03

Sandeep Bansal


2 Answers

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}}" />
like image 136
svick Avatar answered Mar 04 '26 19:03

svick


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();
     }
}
like image 26
Haris Hasan Avatar answered Mar 04 '26 18:03

Haris Hasan