I've come across this problem dealing with subclassing the Windows.UI.Xaml.Button class in C++/CX, and I'd like to know what's going on.
If I subclass the Button control, and add an instance of the subclass to a grid, everything works as expected.
If add an override method of OnApplyTemplate() to the subclass, I get NULL-pointerexception when adding the subclass instance to the grid.
My code looks roughly like this (LayoutRoot is a Grid in MainPage.xaml, this sample has been tested in an empty simple metro application):
// Scenario 1: This works
LayoutRoot->Children->Append(ref new MyButton1());
// Scenario 2: This doesn't work, it will cause a NULL-pointer exception
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 Button {
public:
MyButton2() {};
~MyButton2() {};
virtual void OnApplyTemplate() override {};
};
Note that this question is slightly similar to this question, but the error and the scenario is sufficiently different for me to post this one separately.
UPDATE:
With the Consumer Preview/Visual Studio 11 Beta, this problem has gone away. The OnApplyTemplate() method is virtual, and the OnApplyTemplateCore() method is gone. It took me a while to figure it out, as I got pretty weird compiler errors because of my implementation of the now gone virtual method.
Old answer, applies to the Developer Preview:
The answer makes me feel ashamed for not reading the documentation properly:
The OnApplyTemplate() method is not virtual, so we can't override it. The problem is solved by using the overridable OnUpdateTemplateCore() method instead.
For some reason it worked for me up until a certain point anyway (and the compiler certainly didn't have anything to say about it), but overriding it is absolutely not the right thing to do.