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

如何将Xamarin.Forms的Switch设为全局静态项以在MainPage.cs中访问?

解决方案

方法1:修改XAML字段权限+静态属性暴露

  1. 在XAML的Switch控件中添加x:FieldModifier="public",提升控件的访问级别:
<Switch Grid.Row="1"                
        Grid.Column="1"
        Grid.ColumnSpan="1"
        Margin="{OnIdiom Phone='0, 0, 0, 0', Tablet='0, 0, 0, 155'}"
        x:Name="notificationSwitch"
        x:FieldModifier="public"
        Toggled="notificationSwitch_Toggled"
        IsToggled="{Binding State}"/>
  1. 在MainPage.cs中添加静态属性,页面加载时关联控件:
public static Switch GlobalNotificationSwitch { get; private set; }

protected override void OnAppearing()
{
    base.OnAppearing();
    GlobalNotificationSwitch = notificationSwitch;
}

之后在任意位置都可以通过MainPage.GlobalNotificationSwitch访问这个Switch控件。

方法2:代码后台静态字段关联(无需修改XAML)

直接在MainPage.cs中声明静态字段,通过控件名称查找关联:

public static Switch notificationSwitch;

protected override void OnElementChanged(ElementChangedEventArgs<Page> e)
{
    base.OnElementChanged(e);
    if (e.NewElement != null)
    {
        notificationSwitch = this.FindByName<Switch>("notificationSwitch");
    }
}

后续可直接用MainPage.notificationSwitch访问控件。

注意事项

全局直接操作控件容易引发内存泄漏,更推荐遵循MVVM架构:通过修改绑定的State属性(确保ViewModel实现INotifyPropertyChanged)来控制开关状态,而非直接操作控件实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 21:35:18