首页 > 解决方案 > 在 Windows/UWP/C++ 中使用单击处理程序动态创建按钮

问题描述

我在创建按钮并将其添加到列表视图的方法中有以下代码。但是,当您使用 C++ 而不是 C# 进行编码时,不清楚如何向按钮添加单击事件处理程序。

Button ^ nb = ref new Button();
nb->Content = ref new Platform::String(name.c_str());

nb->Click  // what goes here???

DeviceList->Items->Append(nb);

照明?谢谢你。

标签: windowsuwpclickc++-cx

解决方案


使用 C++ 编码时如何向按钮添加单击事件处理程序

您需要创建一个绑定OnClick回调方法的新 RoutedEventHandler 实例,然后使用+=组合Click事件。当然,您也可以在输入字符Tab后按快捷键。+=

MainPage::MainPage()
{
    InitializeComponent();
    Button ^btn = ref new Button();
    btn->Content = "TestBtn";
    btn->Click += ref new Windows::UI::Xaml::RoutedEventHandler(this, &App5::MainPage::OnClick);
    RootLayout->Children->Append(btn);
}

void App5::MainPage::OnClick(Platform::Object ^sender, Windows::UI::Xaml::RoutedEventArgs ^e)
{
    throw ref new Platform::NotImplementedException();
}

推荐阅读