Home >Backend Development >C++ >How to Safely Cast Generic to Generic in WPF?

How to Safely Cast Generic to Generic in WPF?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-28 18:41:09898browse

How to Safely Cast Generic to Generic in WPF?

The technique of converting generics into generics safely 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.

    Inheritance through generics, inherit the self -based class and realize its own specific functions.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn