我可以在 C++/UWP 中使 EventHandlers 成为非静态成员函数吗?

Can I make EventHandlers non static memberfunctions in C++/UWP?

也许这个问题有点傻,但我现在卡住了。

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

这是我的 class:

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! 
    }
};

`

源自 this case.

Much of OOP can be thought of in terms of message passing.

A method call is a message from the caller to the callee (carrying the parameters) and a message back with the return value.

An event is a message from the source to the subscriber. There are thus potentially two instances involved, the one sending the message and the one receiving it.

With a static event, there is no sending instance (just a type, which may or may not be a class). There still can be a recipient instance encoded as the target of the delegate.

您可以像下面这样为 TextChanged 使用非静态订阅者。

MainPage::MainPage()
{
    InitializeComponent();
    rootLayout = ref new StackPanel;
    
    tbl = ref new TextBlock;
    tb = ref new TextBox;
    rootLayout->Children->Append(tbl);
    rootLayout->Children->Append(tb);
    tb->TextChanged += ref new Windows::UI::Xaml::Controls::TextChangedEventHandler(this, &App17::MainPage::OnTextChanged);
    Content = rootLayout;
}

void App17::MainPage::OnTextChanged(Platform::Object ^sender, Windows::UI::Xaml::Controls::TextChangedEventArgs ^e)
{
    tbl->Text = static_cast<TextBox^>(sender)->Text;
}

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

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

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

ref class Test sealed {
    ...
};

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