Question

I have defined a User control for which I have created a ViewModel. In the code behind of the window where I use this UserControl I set its datacontext to its ViewModel.

I want to access some of the ViewModel's properties in the Code beind of the UserControl.

I am using something like this

var userControlVM = (UserControlVM)this.DataContext;

I am worried about the type casting to UserControlVM since I need to know the type of the VM I am casting, is there any way I can do it without explicitly type casting it like this or is there any other better approach?

Was it helpful?

Solution

There is nothing wrong with a View expecting a particular type of ViewModel. If you need to View to be able to work with different concrete ViewModel types though, you can create an interface like IUserControlVM and have the View cast to that instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top