如何在Xamarin Forms中移除Switch控件的开/关文本
如何在Xamarin Forms中移除Switch控件上的开/关文本?
嘿,要移除Xamarin Forms里Switch控件自带的开/关文本其实不难——因为Forms层面没有直接提供控制这个的属性,咱们得针对不同平台做自定义渲染器来搞定,下面一步步来操作:
第一步:在共享项目创建自定义Switch控件
先在你的共享项目里定义一个继承自原生Switch的自定义控件,这样后续才能给它绑定平台专属的渲染逻辑:
using Xamarin.Forms; namespace YourAppNamespace // 替换成你自己的应用命名空间 { public class CustomSwitch : Switch { // 这里不需要额外代码,只是作为原生Switch的扩展 } }
第二步:针对Android平台添加自定义渲染器
Android原生的Switch默认会显示"开"/"关"(或英文"ON"/"OFF")文本,咱们通过渲染器把这些文本清空:
using Android.Content; using YourAppNamespace; using YourAppNamespace.Droid; // 替换成你Android项目的命名空间 using Xamarin.Forms; using Xamarin.Forms.Platform.Android; // 关联自定义控件和渲染器 [assembly: ExportRenderer(typeof(CustomSwitch), typeof(CustomSwitchRenderer))] namespace YourAppNamespace.Droid { public class CustomSwitchRenderer : SwitchRenderer { public CustomSwitchRenderer(Context context) : base(context) { } protected override void OnElementChanged(ElementChangedEventArgs<Switch> e) { base.OnElementChanged(e); if (Control != null) { // 清空Switch开启和关闭状态的文本 Control.TextOn = ""; Control.TextOff = ""; } } } }
第三步:针对iOS平台添加自定义渲染器
iOS原生的UISwitch默认就不会显示文本,不过为了统一自定义控件的使用,咱们还是添加上对应的渲染器(如果后续有自定义样式需求也能方便扩展):
using YourAppNamespace; using YourAppNamespace.iOS; // 替换成你iOS项目的命名空间 using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; // 关联自定义控件和渲染器 [assembly: ExportRenderer(typeof(CustomSwitch), typeof(CustomSwitchRenderer))] namespace YourAppNamespace.iOS { public class CustomSwitchRenderer : SwitchRenderer { protected override void OnElementChanged(ElementChangedEventArgs<Switch> e) { base.OnElementChanged(e); if (Control != null) { // iOS默认无文本,若后续有自定义文本需求,可通过下面两行清空 // Control.SetTitle("", UIControlState.Normal); // Control.SetTitle("", UIControlState.Selected); } } } }
第四步:在XAML中使用自定义Switch控件
现在回到你的XAML页面,先添加自定义控件的命名空间引用,然后替换原来的Switch为咱们的CustomSwitch:
<!-- 在根元素中添加命名空间(替换成你的应用命名空间) --> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:YourAppNamespace" x:Class="YourAppNamespace.YourPage"> <StackLayout> <Label Text="Below is the binded data: "></Label> <Label Text="{Binding MyData}"></Label> <Label x:Name="lbldisp"></Label> <!-- 使用自定义的CustomSwitch --> <local:CustomSwitch Toggled="SwitchToggled"></local:CustomSwitch> </StackLayout> </ContentPage>
补充说明:UWP平台的原生Switch默认也不会显示文本,所以不需要额外做渲染器处理。
内容的提问来源于stack exchange,提问作者Mohammad Irshad
相关产品推荐
相关产品推荐

