inside
inside

Reputation: 3177

Cast to derived class from DataContext

In my MVVM application I have MyViewModel:

public class MyViewModel : ViewModelBase, IMyViewModel
{
    public virtual RelayCommand MyCommand { get; set; }
}

and DerivedViewModel that extends MyViewModel

public class DerivedViewModel : MyViewModel
{
   private RelayCommand _myCommand; 

   public override RelayCommand MyCommand  
   { 
     get
     {
        if (_myCommand == null)
        {
            _myCommand = new RelayCommand(some implementation...)
        }  
        return _myCommand;
     } 
   }
}

both of viewmodels implement interface IMyViewModel

public interface IMyViewModel 
{ 
    RelayCommand MyCommand { get; set; }
}

Now in my View I am feeding DerivedViewModel as DataContext, and on MouseDoubleClick event, I am trying to cast my DataContext to IMyViewModel to invoke my command:

    private void ListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {   
        if (((FrameworkElement)e.OriginalSource).DataContext != null)
        {
            IMyViewModel viewModel = this.DataContext as IMyViewModel;

            if (viewModel != null)
            {
                viewModel.MyCommand.Execute(((FrameworkElement)e.OriginalSource).DataContext);
            }
        }
    }

However, when I am trying to execute the command it won't find the derived implementation of the command and throw me ObjecNullReference Exception.

I tried to debug and I can confirm that the DataContext is of type DerivedViewModel.

Not sure what I am missing in terms of inheritance/casting.

The problem is that it never casts to the derived class... only assumes that it's a MyViewModel

Upvotes: 0

Views: 1979

Answers (1)

Steve Anderson
Steve Anderson

Reputation: 85

I am not sure how DataContext is getting instantiated, however you have two different instances of them there.

You are getting the first from the event.

if (((FrameworkElement)e.OriginalSource).DataContext != null)

Then you are creating the viewmodel from the local DataContext. Are they supposed to be the same or different?

IMyViewModel viewModel = this.DataContext as IMyViewModel;

If you only have the event one then below makes sense.

static void Main(string[] args)
        {
            if (((FrameworkElement)e.OriginalSource).DataContext != null)
            {
                IMyViewModel viewModel = ((FrameworkElement)e.OriginalSource).DataContext as IMyViewModel;

                if (viewModel != null)
                {
                    viewModel.MyCommand.Execute(viewModel);
                }
            }
        }

Upvotes: 1

Related Questions