Home >Backend Development >C++ >Why Can't I Cast Generic to Generic in WPF UserControls?
WPF UserControl genetic conversion: The conversion problem from derived generics to base class generics
In WPF, when multiple UserControl shares the same features, a base class UserControl is usually defined and incidents are handled in the code hiding of the derived UserControl. However, in some cases, when trying to convert DataContext into genetic type type in the base class UserControl,
exception may be encountered.
InvalidCastException
The abnormal appearance is because the type of DataContext is derived type (for example,
), and you try to convert it to the base type (BaseViewModel<wire>
). This is because cannot be converted to BaseViewModel<connector>
. BaseViewModel
Generic<派生类型>
In conceptual point of view, this is similar to transforming Generic<基类型>
to
, but this will destroy the integrity of List<wolf>
, which may cause inconsistency. List<animal>
List<animal>
The only exception is to use the concepts such as interfaces and using collaborative and inverter, but this is only applicable to the interface, not for classes. Therefore, in your scene, you cannot convert List<wolf>
to
Generic<派生类型>
The above is the detailed content of Why Can't I Cast Generic to Generic in WPF UserControls?. For more information, please follow other related articles on the PHP Chinese website!