Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove on/off text from switch in xamarin forms

Tags:

c#

xamarin

uwp

How to remove on/off text from switch

<Label Text="Below is the binded data: "></Label>
<Label Text="{Binding MyData}"></Label>
<Label x:Name="lbldisp"></Label>
<Switch Toggled="SwitchToggled"></Switch>
like image 983
Mohammad Irshad Avatar asked Jan 03 '18 11:01

Mohammad Irshad


2 Answers

How to remove on/off text from switch

The native control corresponding to the Switch in UWP is ToggleSwitch. If you want to remove on/off content, you could create ToggleSwitch without text style directly in UWP project like following:

App.xaml

<Application.Resources>
    <Style TargetType="ToggleSwitch">
        <Setter Property="OffContent" Value=" " />
        <Setter Property="OnContent" Value=" " />
        <Setter Property="Margin" Value="0,0,-110,0" /> 
    </Style>
</Application.Resources>

![enter image description here

like image 77
W0RT4 Avatar answered Oct 19 '22 23:10

W0RT4


I used an Effect to solve this one.

In your UWP project;

using Windows.UI.Xaml.Controls;
using Xamarin.Forms;
using Xamarin.Forms.Platform.UWP;

[assembly: ResolutionGroupName("YOURAPP")]
[assembly: ExportEffect(typeof(YOURAPP.UWP.Effects.SwitchEffect), nameof(YOURAPP.UWP.Effects.SwitchEffect))]
namespace YOURAPP.UWP.Effects
{
    public class SwitchEffect : PlatformEffect
    {
        protected override void OnAttached()
        {
            if (Control is ToggleSwitch switchControl)
            {
                switchControl.OffContent = string.Empty;
                switchControl.OnContent = string.Empty;
            }
        }

        protected override void OnDetached()
        { }
    }
}

In your Forms project:

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace YOURAPP.Effects
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public class SwitchEffect : RoutingEffect
    {
        public SwitchEffect() : base("YOURAPP.SwitchEffect") { }
    }
}

In your XAML: Add the namespace:

xmlns:effects="clr-namespace:YOURAPP.Effects;assembly=YOURAPP"

<Switch>
    <Switch.Effects>
        <effects:SwitchEffect />
    </Switch.Effects>
</Switch>
like image 39
Sev Avatar answered Oct 20 '22 00:10

Sev