Home >Backend Development >C++ >How to Safely Cast Generic to Generic in WPF?
In WPF, it is a common method to create a base user control that provides derived user control sharing functions. In order to ensure that this function is accessed from derived instances, the event is usually called in the hidden code hidden of the derived user control, for example:
However, the HandleClick method of the base user control may require specific types of parameters:
<code class="language-csharp">private void SomeClick(object sender, RoutedEventArgs e) { HandleClick(sender); MyDataGrid.Items.Refresh(); }</code>
If the DataContext in the derived user control is derived, such as BaseViewModel & LT; wire & gt; This is because DataContext cannot be directly converted to baseViewModel & lt; parts & gt;.
<code class="language-csharp">public class BaseUserControl : UserControl { protected void HandleClick(object sender) { var vm = (BaseViewModel<零件>)DataContext; ... } }</code>
Why can't we convert generic & lt; derived & gt;
It is forbidden to convert generic & lt; derived & gt; converted to generic & lt; base & gt; because it may cause inconsistencies. Imagine, convert List & lt; wolf & gt; convert to list & lt; animal & gt;. You may then add the sheep object to List & lt; animal & gt; although this is not allowed in the original list & lt; wolf & gt; alternative
In order to solve this problem, the following alternative solution can be considered:
Using interfaces instead of generics to define the contract that DataContext must be implemented.
Using a collaborative or inverter interface to forcibly read only the generic types.
The above is the detailed content of How to Safely Cast Generic to Generic in WPF?. For more information, please follow other related articles on the PHP Chinese website!