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

Xamarin ControlTemplate内SwipeView如何通过后台代码打开左侧滑出项

问题原因

ControlTemplate内的控件属于独立的XAML命名范围,和页面的默认命名范围隔离,因此后台代码无法直接通过x:Name直接引用模板内的控件。

解决方法

按照以下步骤即可实现调用:

  1. 在页面对应的后台类中,先声明一个全局的SwipeView变量,用来存储模板内控件的实例:
private SwipeView _swipeMenu;
  1. 重写页面的OnApplyTemplate方法,通过GetTemplateChild方法获取ControlTemplate内的SwipeView实例,这个方法是XAML规范中专门用来获取模板内命名控件的API:
protected override void OnApplyTemplate()
{
    base.OnApplyTemplate();
    _swipeMenu = GetTemplateChild("Swipemenu") as SwipeView;
}
  1. 改造你的按钮点击事件,使用全局变量调用Open方法,加上空判断避免空引用异常:
private void HamDash_Clicked(object sender, EventArgs e)
{
    _swipeMenu?.Open(OpenSwipeItem.LeftItems);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 17:45:05