You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用C++ WinRT API注册Radio的StateChanged事件

C++/WinRT 注册Radio控件StateChanged事件代码示例

你给出的是WinRT中Radio控件StateChanged事件的注册函数签名,以下是可直接使用的注册代码:

// 提前引入所需头文件与命名空间
#include <winrt/Windows.UI.Xaml.Controls.h>
using namespace winrt;
using namespace Windows::UI::Xaml::Controls;

// 假设你已经获取到目标Radio控件实例,变量名为targetRadio
winrt::event_token stateChangedEventToken = targetRadio.StateChanged([](const Radio& sender, const IInspectable& /* 事件参数无额外信息,可忽略 */)
{
    // 此处编写状态变化触发后的业务逻辑
    std::optional<bool> checkState = sender.IsChecked();
    if (checkState.has_value())
    {
        if (checkState.value())
        {
            // 单选框被选中时的逻辑
        }
        else
        {
            // 单选框被取消选中时的逻辑
        }
    }
});

额外说明

  • 取消事件监听:如果后续需要移除该事件绑定,可通过注册时返回的event_token实现:
targetRadio.StateChanged(stateChangedEventToken);
  • 捕获当前类实例的安全写法:如果事件处理逻辑需要用到当前类的成员属性/方法,需使用弱引用捕获避免循环引用导致的内存泄漏,示例如下:
// 该代码写在Page类的成员函数内时的写法
stateChangedEventToken = targetRadio.StateChanged([this_weak = get_weak()](const Radio& sender, const IInspectable&)
{
    // 先校验当前类实例是否存活
    if (auto thisStrongRef = this_weak.get())
    {
        // 可安全调用thisStrongRef指向的类成员
        thisStrongRef->CustomRadioStateHandler(sender.IsChecked().value());
    }
});

内容的提问来源于stack exchange,提问作者Priyanka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 20:48:02