Polymorphism in binding?

时间秒杀一切 提交于 2019-12-11 14:13:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!