为什么在子类Button控件中重写OnApplyTemplate()会导致访问冲突错误? [英] Why does overriding OnApplyTemplate() in a subclassed Button control give access violation error?

查看:73
本文介绍了为什么在子类Button控件中重写OnApplyTemplate()会导致访问冲突错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在处理C ++/CX中的Windows.UI.Xaml.Button类的子类时,我遇到了这个问题,我想知道发生了什么.

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.

如果我将Button控件子类化,并将该子类的实例添加到网格中,那么一切都会按预期进行.

If I subclass the Button control, and add an instance of the subclass to a grid, everything works as expected.

如果将OnApplyTemplate()的重写方法添加到子类中,则在将子类实例添加到网格中时会出现NULL指针异常.

If add an override method of OnApplyTemplate() to the subclass, I get NULL-pointerexception when adding the subclass instance to the grid.

我的代码大致如下(LayoutRoot是MainPage.xaml中的一个Grid,此示例已在一个空的简单Metro应用程序中进行了测试):

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.

推荐答案

更新:

使用Consumer Preview/Visual Studio 11 Beta,此问题已消失. OnApplyTemplate()方法是虚拟的,而OnApplyTemplateCore()方法已消失.我花了一些时间才弄清楚这一点,因为由于实现了现已消失的虚拟方法,我出现了非常奇怪的编译器错误.

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.

旧答案,适用于 Developer Preview :

Old answer, applies to the Developer Preview:

答案使我为未能正确阅读文档感到ham愧:

The answer makes me feel ashamed for not reading the documentation properly:

OnApplyTemplate()方法是不是虚拟的,因此我们不能覆盖它. 通过改用可覆盖的 OnUpdateTemplateCore()方法解决了该问题.

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.

这篇关于为什么在子类Button控件中重写OnApplyTemplate()会导致访问冲突错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆