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

Xamarin.Forms中Expander控件如何监听Expanding展开触发事件?

Xamarin.Forms Expander 展开事件触发实现方案

Xamarin Community Toolkit 提供的 Expander 控件默认没有独立的 Expanding/Expanded 专属事件,你可以通过过滤IsExpanded属性的变更事件来实现仅展开时单次调用指定方法的需求,具体实现方案如下:

方案1:使用现有PropertyChanged事件过滤实现

PropertyChanging和PropertyChanged会在控件所有属性变更时触发,所以只需要过滤出IsExpanded属性的变更即可,后台代码示例如下:

void Expander_PropertyChanged(System.Object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
    // 仅处理IsExpanded属性的变更
    if (e.PropertyName == nameof(Xct.Expander.IsExpanded))
    {
        var expander = sender as Xct.Expander;
        // 仅当控件切换为展开状态时执行目标逻辑
        if (expander != null && expander.IsExpanded)
        {
            // 替换为你需要调用的方法
            YourCustomMethod();
        }
    }
}

如果需要在展开动作执行前触发逻辑,可改用PropertyChanging事件实现,示例如下:

void Expander_PropertyChanging(System.Object sender, Xamarin.Forms.PropertyChangingEventArgs e)
{
    if (e.PropertyName == nameof(Xct.Expander.IsExpanded))
    {
        var expander = sender as Xct.Expander;
        // PropertyChanging触发时属性尚未更新,当前为未展开状态即代表即将执行展开动作
        if (expander != null && !expander.IsExpanded)
        {
            // 替换为你需要调用的方法
            YourBeforeExpandMethod();
        }
    }
}

方案2:MVVM模式下的绑定实现

如果你的项目使用MVVM架构,可直接绑定IsExpanded属性到ViewModel的对应属性,在属性赋值时触发逻辑:

  • XAML代码示例:
<xct:Expander IsExpanded="{Binding IsExpandedState}">
    <!-- 控件内部内容 -->
</xct:Expander>
  • ViewModel代码示例:
private bool _isExpandedState;
public bool IsExpandedState
{
    get => _isExpandedState;
    set 
    {
        SetProperty(ref _isExpandedState, value);
        // 仅展开时触发逻辑
        if (value)
        {
            // 替换为你需要调用的方法
            YourCustomMethod();
        }
    }
}

以上两种方案都可以实现仅在Expander展开时单次调用目标方法,不会被其他无关属性的变更事件干扰。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 16:54:03