Generation of a generic <Derived> into a common <Base>

I have a basic WPF UserControl that handles some common functions for derived UserControls. In the code for any derived UserControl, I raise an event

private void SomeClick(object sender, RoutedEventArgs e) {
    HandleClick(sender);
    MyDataGrid.Items.Refresh();
}

In my UserControl database I am doing

public class BaseUserControl : UserControl {
   protected void HandleClick(object sender) {
       var vm = (BaseViewModel<Part>)DataContext;
       ...
   }
}

This raises an InvalidCastException because it DataContexthas a type BaseViewModel, but a derived type, such as BaseViewModel<Wire>or BaseViewModel<Connector>.

How to do it?

+4
source share
1 answer

You cannot impose Generic<Derived>on Generic<Base>.

, . List<Wolf> List<Animal>. .Add() a Sheep List<Animal>. ... List<Wolf> a Sheep. .

, , , , . . .

+6

Source: https://habr.com/ru/post/1663918/


All Articles