【问题标题】:Where to set the Converter for items of a collection in XAML在 XAML 中为集合项设置转换器的位置
【发布时间】:2011-11-29 21:56:15
【问题描述】:

我刚刚做了我的第一个转换器来从 int 转换为 string。我有一个用整数(年)填充的组合框,但如果值为 0,我希望组合框显示“全部”。

这是我的转换器:

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 中试过:

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

但我总是在这一行得到InvalidcastException

int intY = (int)value;

【问题讨论】:

    标签: c# wpf xaml converter


    【解决方案1】:

    问题是您试图转换整个集合,而不是集合中的一个项目。

    你会想做这样的事情:

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

    【讨论】:

      【解决方案2】:

      您不能像这样使用转换器,ItemsSource 中的转换器应该转换整个集合,而不是单个项目。集合对象不能转换为整数,所以会出现异常。

      您必须使用 DataTemplate 并将转换器应用于单个项目。

      或者 - 如果你只需要转换为 int - 你可以使用ItemStringFormat

      另外,当源为空时设置默认消息,你可以使用绑定的TargetNullValue属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-15
        • 1970-01-01
        • 2011-04-22
        • 1970-01-01
        相关资源
        最近更新 更多