Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
894 views
in Technique[技术] by (71.8m points)

wpf - Is there any way to convert the members of a collection used as an ItemsSource?

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

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}" />

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

  1. Make sure your converter can also deal with collections (IEnumerable).
  2. Use the converter within the item template.

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>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...