Where to set the Converter for items of a collection in XAML

我怕爱的太早我们不能终老 提交于 2020-01-04 03:55:08

问题


I just made my first converter to convert from int to string. I have a combobox fill with integers(years) but if the value is 0 I want the combobox to show 'All'.

This is my converter:

public class IntToString : IValueConverter
{
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value != null)
            {
                int intY = (int)value;

                if (intY == 0)
                {
                    String strY = "All";
                    return strY;
                }
                else
                {
                    return intY.ToString();
                }
            }

            return String.Empty;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {

        }
    }

In XAML where should I set the converter ? I tried in the ItemsSource of the combobox:

ItemsSource="{Binding YearsCollection, Converter={StaticResource intToStringYearConverter}}"

But I always get InvalidcastException on this line:

int intY = (int)value;

回答1:


The problem is that you are trying to convert the entire collection rather than just one item from the collection.

You would want to do something like this:

<ListBox ItemsSource="{Binding YearsCollection}">
    <ListBox.ItemTemplate>
        <DataTemplate>
             <Border DataContext="{Binding Converter={StaticResource intToStringYearConverter}">
             ...
             </Border>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>



回答2:


You can't use the converter like this, converter in ItemsSource is supposed to convert whole collection, not individual items. The collection object can't be cast to integer, so you get the exception.

You have to use DataTemplate and apply the converter on individual items.

Or - if all you need is cast to int - you could use ItemStringFormat.

Also, for setting the default message when the source is null, you can use TargetNullValue property of a Binding.



来源:https://stackoverflow.com/questions/7635170/where-to-set-the-converter-for-items-of-a-collection-in-xaml

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!