首页 > 解决方案 > 我可以在 C++/UWP 中使 EventHandlers 成为非静态成员函数吗?

问题描述

也许这个问题有点愚蠢,但我现在被困住了。

我目前正在研究一个带有 TextBox 和 TextBlock 的类。当您在 TextBox 中键入内容时,TextChangedEventHandler 应该使用相同的文本更新 TextBlock。但是因为 EventHandler 函数是静态的,所以我无法获取 TextBlock,因为它当然是非静态的。有没有办法正确地做到这一点,或者可以使 EventHandlers 非静态?

这是我的课:

class Test {
    TextBlock^ tbl;
    TextBox^ tb;
public:
    Test(StackPanel^ parent) {
        tbl = ref new TextBlock;
        tb = ref new TextBox;
        tb += ref new Windows::UI::Xaml::Controls::TextChangedEventHandler(&tb_TextChanged);
        parent->Children->Append(tbl);
        parent->Children->Append(tb);
    }
    static void tb_TextChanged(Platform::Object ^sender, Windows::UI::Xaml::Controls::TextChangedEventArgs ^e) {
        tbl->Text = static_cast<TextBox^>(sender)->Text; //this doesnt work unfortunately! 
    }
};

`

标签: c++uwpeventhandler

解决方案


好的,首先感谢 Hans Passant 和 Nico Zhu 的帮助。我无法使用:

tb->TextChanged += ref new Windows::UI::Xaml::Controls::TextChangedEventHandler(&tb_TextChanged);

因为我的课是标准的 c++ 课。我必须先将其声明为 C++/CX,例如:

ref class Test sealed {
    ...
};

但是有了这个定义,我现在可以将“this”传递给函数。<3


推荐阅读