在XAML中为集合项设置转换器的位置 [英] Where to set the Converter for items of a collection in XAML

查看:85
本文介绍了在XAML中为集合项设置转换器的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚使我的第一个转换器从int转换为string。我有一个用整数(年)填充的组合框,但是如果值是0,我希望组合框显示'All'。

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'.

这是我的转换器:

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)
        {

        }
    }

在XAML中,应该在哪里设置转换器?我在组合框的ItemsSource中尝试过:

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

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

但是我总是在这行得到 InvalidcastException

But I always get InvalidcastException on this line:

int intY = (int)value;


推荐答案

问题是您正在尝试转换整个

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>

这篇关于在XAML中为集合项设置转换器的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆