如何转换List< T>列出< dynamic>WPF [英] How to convert List<T> to List<dynamic> WPF

查看:83
本文介绍了如何转换List< T>列出< dynamic>WPF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我有一个列表框

<ListBox ItemsSource="{Binding MyList}"/>

我有一个财产:

private List<dynamic> _myList;

public List<dynamic> MyList
{
    get { return _myList; }
    set
    {
        if(value==null)return;
        _myList = value;
        OnPropertyChanged();
    }
}

好的,现在我们要问我的问题:我有几个类,它们将具有列表,我希望能够在此ListBox中显示它们.

okay, now we're getting to my question: I have Several classes that I will have Lists of and I would like to be able to display them in this ListBox.

课程:

public class A
{
    public string S { get; set; }
    public int I { get; set; }
}

public class B
{
    public int C { get; set; }
    public string Name { get; set; }
    public string F { get; set; }
}

public class C
{
    public int I { get; set; }
    public string Name { get; set; }
    public string This { get; set; }
    public double That { get; set; }
}

填写我的列表

    private void FillA()
    {
        List<A> listA = GetListAFromSomewhere();

        MyList = listA;
    }
    private void FillB()
    {
        List<B> listb = GetListBFromSomewhere();

        MyList = listb;
    }

    private void FillC()
    {
        List<C> listC = GetListCFromSomewhere();

        MyList = listC;
    }

我收到异常

无法隐式转换类型'System.Collections.Generic.List'到'System.Collections.Generic.List'

Cannot implicitly convert type 'System.Collections.Generic.List' to 'System.Collections.Generic.List'

我试图进行投射,并寻找一个转换器.但似乎无法弄清楚.当我更改为 List< object> 时,它的作用相同.

I have tried to cast, and looked for a converter. but cannot seem to figure it out. It does the same when I change to List<object>. this

感谢您的帮助!

推荐答案

我认为您的问题是由协方差/convarivariance引起的.类不支持此功能.您可以使用接口或Cast linq方法.在此处查看更多信息: https://msdn.microsoft.com/en-us/library/ee207183.aspx 我的意思是这样的:

I think that your issue caused by covariance/contrvariance. Classes don't support this feature. You can use interface or Cast linq method. See more here: https://msdn.microsoft.com/en-us/library/ee207183.aspx I mean something like this:

MyList = GetListAFromSomewhere().Cast<dynamic>().ToList();

也不确定您的ListBox是否可以与dynamic一起正常使用.您可以在XAML中使用继承和TemplateSelector: http://www.codeproject.com/Articles/418250/WPF-Based-Dynamic-DataTemplateSelector

Also not sure if your ListBox will work properly with dynamic. You could use inheritance and TemplateSelector in XAML: http://www.codeproject.com/Articles/418250/WPF-Based-Dynamic-DataTemplateSelector

这篇关于如何转换List&lt; T&gt;列出&lt; dynamic&gt;WPF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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