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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With