Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert List<T> to List<dynamic> WPF

Tags:

c#

wpf

Lets say I have a Listbox

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

I have a Property:

private List<dynamic> _myList;

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

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.

Classes:

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; }
}

Filling myList

    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;
    }

I get Exception

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

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

thanks for the help!

like image 381
JamTay317 Avatar asked Dec 04 '22 01:12

JamTay317


1 Answers

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();

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

like image 124
Andrew Avatar answered Dec 21 '22 22:12

Andrew