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

如何在WinUI 3桌面应用中通过代码触发Button的Click事件?

在WinUI 3桌面应用中通过代码触发Button的Click事件(无法访问内部处理程序时)

我希望在WinUI 3桌面应用中通过代码触发Button的Click事件。在Stack Overflow上查了很多相关问题,发现答案都是直接调用事件处理程序(比如使用命令或直接调用方法等),而非真正触发Button本身的事件。

如果能访问处理程序,这种方法没问题,但如果处理程序是内部的、无法访问的情况呢?比如Button嵌入在复杂控件中,其处理程序包含复杂(或未知)的额外逻辑。

举个实际场景:我最近尝试重新格式化DatePicker控件——它对内部TextBlock和LoopingSelector的尺寸及布局有自己的逻辑。我试过重写Style、派生Control、使用MeasureOverride和ArrangeOverride等常规方法,但都无效,显然DatePicker的格式化逻辑是在内部代码中实现的。最终我隐藏了DatePicker自带的FlyoutButton,添加了自定义按钮ReplacementFlyoutButton。现在我希望这个自定义按钮能触发原FlyoutButton的处理程序,从而生成正确的Flyout并完成日期本地化等操作。

通过在派生类中重写OnApplyTemplate方法,我已经能获取到DatePicker底层的FlyoutButton:

protected override void OnApplyTemplate()
{
    base.OnApplyTemplate();

    // Tree looks like:
    // this as DatePicker
    //  LayoutRoot as Grid
    //   HeaderContentPresenter as ContentPresenter
    //   FlyoutButton as Button
    //    FlyoutButtonGrid as Grid
    //     ContentPresenter as ContentPresenter
    //      FlyoutButtonContentGrid as Grid
    //       DayTextBlock as TextBlock
    //       MonthTextBlock as TextBlock
    //       YearTextBlock as TextBlock
    //       FirstPickerSpacing as Rectangle
    //       SecondPickerSpacing as Rectangle
    DayTextBlock = GetTemplateChild("DayTextBlock") as TextBlock;
    MonthTextBlock = GetTemplateChild("MonthTextBlock") as TextBlock;
    YearTextBlock = GetTemplateChild("YearTextBlock") as TextBlock;
    FirstPickerSpacing = GetTemplateChild("FirstPickerSpacing") as Rectangle;
    SecondPickerSpacing = GetTemplateChild("SecondPickerSpacing") as Rectangle;
    FlyoutButtonContentGrid = GetTemplateChild("FlyoutButtonContentGrid") as Grid;
    FlyoutButton = GetTemplateChild("FlyoutButton") as Button;
    _replacementFlyoutButton = GetTemplateChild("ReplacementFlyoutButton") as Button;

    if (_replacementFlyoutButton is not null) { _replacementFlyoutButton.Click += OnReplacementFlyoutButtonClick;}
}

请问能否在OnReplacementFlyoutButtonClick()方法中触发DatePicker或其FlyoutButton的Click事件?

补充说明:DatePicker和FlyoutButton的ContextFlyout均不为空,且FlyoutButton的Flyout为空。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:25:23