1

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?

4

1 回答 1

4

期望特定类型的 ViewModel 的 View 没有任何问题。但是,如果您需要 View 才能使用不同的具体 ViewModel 类型,您可以创建一个类似 IUserControlVM 的接口,并将 View 转换为该接口。

于 2013-09-18T04:51:36.593 回答