问题
I have a POCO objects (public class with lots of public fields).
public class Poco
{
public string name1;
public string name2;
public bool isName1Used;
}
Now i need to render a list of objects names, but with one condition: depending on bool, should be used name1 or name2. So, i made inherited class and add some functionality there
public class Item : Poco
{
public string Name
{
get { return isName1Used ? name1 : name2; }
}
How can i now say to binding engine that it should bind to the Name?
<TextBlock Text="{Binding Name}"/>
It says, Name is not found in Poco (fair enough, because engine doesn't know that it can polymorph Poco to Item).
回答1:
Well, you have to bind Item
and not Poco
elements to the view. Polymorphism isn't implicit just because you created an inherited class, you need to actually construct instances of that class and bind them.
var pocos = new List<Poco>();
var items = pocos.Select(i=>new Item
{
name1 = i.name1,
name2 = i.name2,
isName1Used = i.isName1Used
});
来源:https://stackoverflow.com/questions/22067897/polymorphism-in-binding