有什么方法可以转换用作 ItemsSource 的集合的成员吗? [英] Is there any way to convert the members of a collection used as an ItemsSource?

查看:24
本文介绍了有什么方法可以转换用作 ItemsSource 的集合的成员吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 WPF 中,您可以使用 IValueConverter 或 IMultiValueConverter 将数据绑定值从 int 转换为 Color.

In WPF you can use an IValueConverter or IMultiValueConverter to convert a data-bound value from say an int to a Color.

我有一组 Model 对象,我想将它们转换为它们的 ViewModel 表示,但在这种情况下,

I have a collection of Model objects which I would like to convert to their ViewModel representations but in this scenario,

<ListBox ItemsSource="{Binding ModelItems, 
     Converter={StaticResource ModelToViewModelConverter}" />

将编写转换器以一次转换整个集合 ModelItems.

the converter would be written to convert the whole collection ModelItems at once.

我想单独转换集合的项目,有没有办法做到这一点?我可能想使用 CollectionViewSource 并有一些过滤逻辑,所以我不想在每次发生变化时都遍历整个集合.

I wish to convert the items of the collection individually, is there a way to do that? I might want to use a CollectionViewSource and have some filtering logic so I don't want to have to iterate over the whole collection every time something changes.

推荐答案

您不能在集合本身上设置转换器,因为它会将集合作为输入.你有两个选择:

You cannot set the converter on the collection itself, because it would get the collection as input. You have two choices:

  1. 确保您的转换器也可以处理集合 (IEnumerable).
  2. 在项目模板中使用转换器.

如果您想使用第二种方法,请使用以下方法:

If you want to use the second approach, then use something like this:

<ListBox ItemsSource="{Binding ModelItems}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <ContentPresenter Content="{Binding Converter={StaticResource ModelToViewModelConverter}}" 
                        ContentTemplate="{StaticResource MyOptionalDataTemplate}"/>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

如果您不需要自定义数据模板,则可以跳过 ContentTemplate 属性.

If you don't need a custom datatemplate, then you can skip the ContentTemplate attribute.

这篇关于有什么方法可以转换用作 ItemsSource 的集合的成员吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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