Get type of items in ObservableCollection
I have a view (consists of a list) that is bound to some observable collection. In other words, I:
var someCollection = new ObservableCollection<ClassFoo>();
// initialize someCollection
ListView someView = new ListView();
someView.DataContext = someCollection;
someView.ItemsSource = someCollection;
Note:
-
someView
located on Project1.dll andsomeCollection
on Project2.dll - Project2.dll is referenced to Project1.dll AND Project1.dll is NOT referenced to Project2.dll
So in my opinion I have a reference to someCollection of type ObservableCollection<object>
, because I will get a compilation error if it has its actual type ObservableCollection<ClassFoo>
, because I will need to add a reference to Project2.dll.
For some reason I cannot add this link and I my boss wants me to create teams, etc.
The last part just explains why I want to do this, but in short I am looking for:
ObservableCollection<object> myUnknownObservableCollection = someReference;
// I know that someReferce is of type ObservableCollection<ClassFoo>
var x = myUnknownObservableCollection.GetType().GetTypeOfItems.....
in the end I will need x to be equal typeof(ClassFoo)
, how can I do this with reflection given that someReference is of type ObservableCollection<ClassFoo>
?
Edit
I have a solution! Here he is:
class Person
{
public string Name { get { return "Antonio"; } }
}
..
// view code:
IEnumerable<object> uncknownObject;
// view model does this:
uncknownObject = new ObservableCollection<Person>( );
// continuation of view code:
var observCol = uncknownObject.GetType( );
var x = ( ( dynamic )observCol ).GenericTypeArguments[ 0 ];
var instance = ( Person )Activator.CreateInstance( x );
Console.WriteLine( instance.Name ); // Print Antonio!!!
It would be nice to be able to do this without a dynamic datatype, but
Edit 2
Here is a solution running .net 4.0 without using dynamic type
source to share
If you plan on using mvvm, a dynamic type will not help with binding. You may need to use the interface that SLaks suggested
public interface IClassFoo
{
string Name { get; }
}
public class ClassFoo : IClassFoo
{
public string Name { get { return "Antonio"; } }
}
//Usage
var someCollection = new ObservableCollection<IClassFoo>();
source to share