开发者

Distinct Values in WPF Combobox Error

I have the current Combo Box XAML:

        <ComboBox Height="23" HorizontalAlignment="Left" ItemsSource="{Binding ElementName=showDomainDataSource, Path=Data}" Margin="583,8,0,0" x:Name="showsComboBox" VerticalAlignment="Top" Width="233" SelectionChanged="showsComboBox_SelectionChanged" IsSynchronizedWithCurrentItem="False">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="{Binding Path=showName, Converter={StaticResource distinctConverter}}" x:Name="showsComboxshowName" />
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemp开发者_如何学编程late>
        </ComboBox>

And I have the class - DistinctConverter:

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

I have added the following to my resources:

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

The problem is, I'm getting the error in my combo box:

Distinct Values in WPF Combobox Error

Can anyone help me with whatever I'm doing wrong here.


The problem is that the showName property in your model is returning a collection which you want to bind to the Text property of a TextBox which is a string. Then you have a converter that takes a collection as input, runs a LINQ query on it, which returns another collection. That value, the whole collection, is being converted by the binding to a string using ToString and being displayed as a single entry in your combo box. And then that process is repeated for each item in the combo box.

Without knowing exactly what you are trying to accomplish, it's hard to suggest exactly how to fix this. For example, if showName is equal to:

string[] { "Bill", "Bill", "Mike", "Ted" };

Would you like this to appear in the combo box row?

Bill Mike Ted

If so, then you can use Aggregate after you use Distinct.

But it sounds more likely that you want Bill, Mike and Ted to appear as separate items in the combo box. In that case you need to apply the converter to the ItemsSource for the ComboBox itself instead of the TextBox in the ItemTemplate.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜