2

Assuming you have a Grid with an ItemsSource-Property (DataGrid.ItemsSource). This property is been set during runtime. A possible object could be the following:

public partial class InstantFeedbackCollectionViewModel<TEntity, TPrimaryKey, TUnitOfWork> 
   : InstantFeedbackCollectionViewModelBase<TEntity, TEntity, TPrimaryKey, TUnitOfWork>

Later during runtime I want to catch an Event and want to check whether the ItemsSource of the grid is of the type above.

Usually I would do something like that:

if (typeof(datagrid.ItemsSource) is InstantFeedbackCollectionViewModel) then ...

But how can I do this with this generic class?

UPDATE:

In the second step I would like to execute a method in the InstantFeedbackCollectionViewModel. Something like that:

if (datagrid.ItemsSource.GetType().GetGenericTypeDefinition() == typeof(InstantFeedbackCollectionViewModel<,,>) {
var instFeedbackCollectionViewModel = grid.ItemsSource;
instFeedbackCollectionViewModel.ExecuteMyMethod();
}

Does one know how to do this?

SaschaR
  • 23
  • 5

1 Answers1

2

If you want to know whether the type is a generic InstantFeedbackCollectionViewModel you can use this code :

bool isInstantFeedbackCollectionViewModel = 
      datagrid.ItemsSource.GetType().GetGenericTypeDefinition() ==
      typeof(InstantFeedbackCollectionViewModel<,,>);

If you want to know whether the type inherits from a generic InstantFeedbackCollectionViewModel then see Check if a class is derived from a generic class.

Community
  • 1
  • 1
Guillaume
  • 12,824
  • 3
  • 40
  • 48
  • That's exactly what I wanted in the first step. – SaschaR Oct 16 '15 at 11:28
  • Yes. Do you have an idea to my additional question as well? – SaschaR Oct 16 '15 at 12:50
  • @SaschaR, define an interface IInstantFeedbackCollectionViewModel exposing the appropriate method. Implement it from InstantFeedbackCollectionViewModel<,,> then try to cast ItemSource as this interface. – Guillaume Oct 16 '15 at 15:11