简体   繁体   English

将XamlComboBox强制转换为继承的类型

[英]Casting XamlComboBox to a inherited Type not working

I am trying to cast a CodedUI XamlControl to a Type of a XamlComboBox but the cast throws a unable to cast exception. 我正在尝试将CodedUI XamlControl XamlControl转换为XamlControl的类型,但是XamlComboBox引发无法XamlComboBox转换的异常。

My class is: 我的课是:

public class MyComboBox : XamlComboBox

The error occurs when i try to iterate over a List<XamlControl> in the following line: 当我尝试遍历以下行中的List<XamlControl> ,将发生错误:

var comboBox = (MyComboBox) element;

Even when i try something weird like this: 即使我尝试像这样的怪异的东西:

var xamlComboBox = (XamlComboBox) element;
var comboBox = (MyComboBox) xamlComboBox;

the error still hapens at cast to MyComboBox 该错误仍然很可能投射到MyComboBox

Any idea, why this is happening? 任何想法,为什么会这样?

Before your iteration filter all items, which are not of type MyComboBox : 在迭代之前,过滤所有不是MyComboBox类型的MyComboBox

List<XamlControl> controls = ...
foreach (var comboBox in controls.Where(c => c is MyComboBox)) {
    // Here the items are only of type MyComboBox
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM