In WPF, when the derived UserControl inherits the self -based class and shared public functions, the code hidden by the derived UserControls may reference the base class processing. However, access to DataContext from the base class may cause InvalidCastexception because it is a derivative type in the derivative UserControls.
Let's take a look at an example:
<code class="language-csharp">private void SomeClick(object sender, RoutedEventArgs e) { HandleClick(sender); MyDataGrid.Items.Refresh(); }</code>
In the base class UserControl:
<code class="language-csharp">public class BaseUserControl : UserControl { protected void HandleClick(object sender) { var vm = (BaseViewModel<Part>)DataContext; ... } }</code>
This will cause InvalidCastexception, because the DataContext type in UserControls may be BaseViewModel
Why can't it be changed directly?
converting geneic & lt; derived type & gt; converted to generic & lt; base type & gt; is essentially unsafe. Consider the following example:
If this conversion is allowed, a sheep is added to Animals, and it is actually allowed to add it to Wolves, causing the type to not match.Solution
<code class="language-csharp">List<wolf> wolves = new List<wolf>(); List<animal> animals = (List<animal>)wolves; // 无法转换</code>
In order to solve this problem, the collaboration or inverter of the interface can be forced to read only the required type. However, this method can only be feasible only when the class you referenced achieves the necessary interface. This requires adjustment of the code structure. For example, using the interface to define the type of DataContext, and use the collaborative or inverse characteristics. The specific implementation depends on the definition and actual needs of .
The above is the detailed content of How to Safely Cast Generic to Generic in WPF UserControls?. For more information, please follow other related articles on the PHP Chinese website!