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 b开发者_如何学Golue 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:
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}}" />
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();
}
}
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();
精彩评论