我在处理 C++/CX 中的 Windows.UI.Xaml.Button 类的子类时遇到了这个问题,我想知道发生了什么。
如果我将一个控件实例添加到网格中,一切都会按预期工作。
如果我对控件进行子类化并添加一个实例subclass,一切都按预期进行。
但如果我子类化我的子类化控件并将其实例添加到网格中,我在 Grid::Children::Append() 期间抛出 E_INVALIDARG。是什么赋予了?
我的代码大致如下所示(LayoutRoot 是 MainPage.xaml 中的一个网格,该示例已在空的简单 Metro 应用程序中进行了测试):
// Scenario 1: This works (duh!)
LayoutRoot->Children->Append(ref new Button());
// Scenario 2: This works
LayoutRoot->Children->Append(ref new MyButton1());
// Scenario 3: This doesn't work, it will cause an E_INVALIDARG to be thrown by the collection
LayoutRoot->Children->Append(ref new MyButton2());
// This is how MyButton1 and MyButton2 is defined
public ref class MyButton1 : public Button {
public:
MyButton1() {};
~MyButton1() {};
};
public ref class MyButton2 : public MyButton1 {
public:
MyButton2() {};
~MyButton2() {};
};
请注意,这个问题与这个问题,但错误和场景完全不同,我可以单独发布此错误。
UPDATE:我认为阅读后我理解这个问题的方向是正确的伊恩·格里菲斯的这篇文章,但我需要更多地了解这个特定示例的行为。可以找到重复此问题的完整代码在这里,请参阅线程中的第 3 篇文章.
UPDATE:据我目前所知,并非所有 WinRT 类型都支持继承。我对此没有可靠的源参考,但我读到 Windows.UI.Xaml 类应该支持继承,但其他 WinRT 类型不会。 Windows.UI.Xaml.Controls.Button 类显然可以,而我自己的 MyButton1 则不能。我想知道我必须做什么才能使 MyButton1 像 Button 类一样“可继承”。
我发现用 Windows.UI.Xaml.Controls.ProgressBar 替换 Windows.UI.Xaml.Controls.Button 类将使方案 2 失败,这告诉我 ProgressBar 类(尚)不可能进行子类化。这一观察使我相信一个类需要做一些明确的事情才能使其可继承。