To build on a post I saw here:
C# - Multiple generic types in one list
I want to bind a WPF DataGrid to the ClassAClassBCombinedList property something like:
<DataGrid ItemsSource="{Binding ClassAClassBCombinedList.Data}" />
for the property:
public List<CombinedClass> ClassAClassBCombinedList
{
get
{
List<CombinedClass> result = new List<CombinedClass>();
result.Add(new CombinedClass<ClassA>(new ClassA()));
result.Add(new CombinedClass<ClassB>(new ClassB()));
return result;
}
}
With CombinedClass defined as:
public interface CombinedClass { }
public class CombinedClass<T> : CombinedClass where T : class
{
public CombinedClass(T classInstance)
{
Data = classInstance;
}
public T Data { get; private set; }
}
But this doesn't work because:
'CombinedClass' does not contain a definition for 'Data' and no extension method 'Data' accepting a first argument of type 'CombinedClass'
You can access the Data member by casting, however this defeats the point.
((CombinedClass<ClassA>)ClassAClassBCombinedList.First()).Data;
Any ideas on how to combine a list with multiple class types and bind to them in WPF??
Your problem is not the cast. The problem is, that ClassAClassBCombinedList returns a List, whereas the property Data is a property of each instance in the list!
Additionally, your interface CombinedClass is useless, because it doesn't provide anything. You should put something like object Data in it and overwrite the property in CombinedClass<T> with the new keyword.
In general, I am not sure, this is a good idea to do, even though it is the accepted answer in the linked question.
Why don't you make your ClassA and ClassB use the same interface IClass which defines the Data property? Then you can make a List<IClass> which can contain ClassA as well as ClassB and which you can bind to your DataGrid.
public interface IClass
{
object Data {get; set; }
}
public class ClassA : IClass
{
// implement `Data` property
}
public class ClassB : IClass
{
// implement `Data` property
}
{
// make the list by adding objects of type `ClassA` or `ClassB`, don't forget to set their `Data` property
List<IClass> result = new List<IClass>();
result.Add(new ClassA());
result.Add(new ClassB());
}
And Bind it
dataGrid.ItemsSource = result // List<IClass>
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