I'm creating my first Android App in VS 2022 with Xamarin and now I have to bind a switch to a label to show the user what on/off means. Multiple times so I made a content view:
<ContentView xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:controls="clr-namespace:App1.Controls" x:DataType="controls:SwitchWithText"
x:Class="App1.Controls.SwitchWithText"
x:Name="root">
<ContentView.Content>
<StackLayout Orientation="Horizontal">
<Label x:Name="isOkLbl" Text="is not ok" Margin="10"/>
<Switch x:Name="switch1" IsToggled="{Binding Path=IsToggled}"/>
</StackLayout>
</ContentView.Content>
</ContentView>
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
namespace App1.Controls
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SwitchWithText : ContentView
{
public static readonly BindableProperty isToggledProperty = BindableProperty.Create(
nameof(isToggledProperty), //name of property
typeof(bool), //type of property
typeof(SwitchWithText), //type of owning object
defaultValue: false,
propertyChanged: IsToggledChanged);
public bool IsToggled
{
get => (bool)GetValue(isToggledProperty);
set => SetValue(isToggledProperty, value);
}
private static void IsToggledChanged(BindableObject bindable, object oldValue, object newValue)
{
var control = (SwitchWithText)bindable;
if (control != null && control.switch1.IsToggled)
{
control.isOkLbl.Text = "is ok";
}
else
{
control.isOkLbl.Text = "is not ok";
}
}
public SwitchWithText()
{
BindingContext = this;
InitializeComponent();
}
}
}
Some stuff is auto complete by Visual Studio 2022 and looks like it'd do what I need but nothing happpens when I toogle the switch. :( Or is there an even better way to do this? I saw pictures of switches with text on it but couldn't find something like that in Xamarin.
