How to convert items from itemssource
how can I convert a single Item from an Itemssource to another Item?
For example, I have a collection of TypeA which is not directly tied to a TypeB, but I need to Access TypeB in the ItemTemplate.
<DataGrid ItemsSource={Binding SomeCollectionOfTypeAWhichCanBeConvertedByAlgorithm}>开发者_Go百科
<DataGridTextColumn Binding="{Path=PropertyOfTypeB}" />
</DataGrid>
I ended up using a Pair class and binding the itemssource to the collection.
Example:
<DataGrid ItemsSource="{Binding CollectionOfTypeAWhichCanBeConvertedToTypeB}" >
<DataGridTextColumn Binding="{Binding Path=PropertyOfTypeB}" />
</DataGrid>
I search a method to convert the item of the collection from TypeA to TypeB inside the template. I cannot use a converter for the Property-Binding, since I need to maintain the reference.
And I cannot have a reference to A in B and vice versa.
Unless TypeA is a subtype of TypeB it's just not going to work. Your best bet is to convert the items to typeB before you bind them to the ItemSource.
Try Automapper if it fits, or perhaps if it's .NET 4, dynamics.
What you're going to need to do is extend your view model so that it exposes a collection of type B. Internally it will look something like:
public ObservableCollection<TypeA> ItemsOfTypeA { get; set; }
private ObservableCollection<TypeB> _ItemsOfTypeB;
public ObservableCollection<TypeB> ItemsOfTypeB
{
get
{
if (_ItemsOfTypeB == null)
{
var converted = ItemsOfTypeA.Select(ConvertTypeAToTypeB);
_ItemsOfTypeB = new ObservableCollection<TypeB>(converted);
}
return _ItemsOfTypeB;
}
}
private TypeB ConvertTypeAToTypeB(TypeA a)...
I've made the collections observable in this example under the assumption that the TypeA collection will be changing, and you need those changes to propagate to the UI - you'll need to handle the CollectionChanged
event on that property and deal with adding items, removing items, and refreshing the TypeB collection when it's raised. This does mean that you'll also need a way of knowing which TypeA object created a given TypeB object, so that you'll know which object to remove from the TypeB collection when a TypeA object gets removed.
精彩评论