Do you know if there is a way to unwrap some object which is known to derive from some base class.
I have a view which can host multiple different view models at run time. I would like to invoke some common behavior for the datacontext of that view.
Since DataContext is wrapped into ObjectInstance<T> I can't cast it in the following manner.
public class ViewModelBase : IViewModel
public class SomeViewModel : ViewModelBase
public class MainViewModel : ViewModelBase
... in App.cs I set DataContext = ForView.Wrap(MainViewModel)
... via data binding at run-time SomeView gets some DataContext of type SomeViewModel or any other view model derived from ViewModelBase, this determined at run-time.
... in SomeView.cs I would like to know what kind of model is attached to it so that we can load a proper view for a view model. So I do this
ViewModelBase item = ForView.Unwrap<ViewModelBase>(DataContext)
// this technically should not work, because generics to not support casting to derived types.
But I know that all the objects wrapped in ObjectInstance derive from ViewModelBase.
This is what I tried:
Implementing interface condition in ObjectInstance like so
where IViewModel defines behavior and ViewModelBase implements it.
Then I tired casting like so:
<font size="2" color="#2b91af"><font size="2" color="#2b91af">
</font></font><font size="2" color="#2b91af">
item = ForView.Unwrap<IViewModel>(this.DataContext)
But this still doesn't work.
Do you know if there is a proper way to get around this problem?
Maybe have a non-generic public Object ForView.Unwrap(ObjectInstance DataContext)?
Or maybe ObjectInstance<T> can inherit from non-generic ObjectInstance, and within generic class override a method which returns wrapped object as Object (this actually works for me)?
public abstract class ObjectInstance
public abstract Object GetWrappedObject();
public class ObjectInstance<TWrappedObjectType> : ObjectInstance, IObjectInstance, INotifyPropertyChanged, IDataErrorInfo
public override object GetWrappedObject()
// ... the rest of the code.
Basically I have a list of items in some higher level MainViewModel. All items derive from ViewModelBase, this list is an ItemSource for ListView control in a view which has MainViewModel as its datacontext. Template of this ListView has some container
user control which suppose to load appropriate view based on its current DataContext. But I can't get to DataContext object because it is wrapped.