The challenge of genetic conversion in the type of generic type in WPF applications
In WPF applications, the conversion between generic types is sometimes tricky. A special scene involves converting
types into type. Generic<派生类型>
Generic<基类型>
Assuming you have a base WPF UserControl for multiple derivative UserControl. In each derived UserControl code hidden, the event processing program calls the method in the userControl. However, when you try to
in the use of DataContext
when you try to convert Generic<基类型>
in the basis of UserControl. InvalidCastException
or DataContext
, and the UserControl expects it is an instance of BaseViewModel<线>
. BaseViewModel<连接器>
Generic<基类型>
Core concept understanding
Unfortunately, cannot be converted to
directly. This is a basic limit for generic systems. To explain this, suppose you can execute such a conversion.
Generic<派生类型>
Suppose you have a Generic<基类型>
, you convert it to
to . However, this will lead to logic inconsistent, because List<狼>
will now include a List<动物>
. List<动物>
羊
alternative List<狼>
羊
Implementing public interface:
If your derivative types implement a public interface (for example,), you can convert
to the interface and access public functions in this way.IBaseViewModel
DataContext
The above is the detailed content of How to Overcome Casting Challenges with Generics in WPF Applications?. For more information, please follow other related articles on the PHP Chinese website!