locked
Why does overriding OnApplyTemplate() in a subclassed Button control give access violation error?

    Question

  • 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 {};
    };






    Wednesday, February 15, 2012 3:56 AM

Answers

  • I'm sorry for not reading the documentation properly. OnApplyTemplate() is not virtual, and though the compler doesn't complain (and though it'll work sometimes), it is not the right method to override.

     

    The correct method to override is OnApplyTemplateCore(), and then it works.


    Wednesday, February 15, 2012 4:46 AM