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