I have this graphical interface:
Where the label "Weight: 70 kg" shows the weight that has been selected in the slider below the label by the user.
Is there a way so that when you activate the switch, the label that shows the weight changes from kg to lbs and vice versa?
- Active switch shows weight in pounds.
- Inactive switch shows weight in kilos.
Example in the image is "Weight: 70kg" once the switch is activated "Weight: 155 lbs" will be displayed .
<Label x:Name="Imperial_System_Label"
Grid.Row="3"
Grid.ColumnSpan="3"
Text="Imperial System"
TextColor="Black"
FontSize="22"
HorizontalOptions="Center"/>
<Switch x:Name="Switch"
Grid.Row="4"
Grid.ColumnSpan="3"
HorizontalOptions="Center"
Toggled="Handle_Toggled"/>
<Label x:Name="Height_Label"
Grid.Row="5"
Grid.ColumnSpan="3"
BindingContext="{x:Reference Height_Slider}"
Text="{Binding Value, StringFormat='Height: {0:F0} cm'}"
TextColor="Black"
FontSize="22"
HorizontalOptions="Center"/>
<Slider Grid.Row="6"
Grid.ColumnSpan="3"
x:Name="Height_Slider"
Maximum="240"
Minimum="135"
Value="170"/>
<Label x:Name="Weight_Label"
Grid.Row="7"
Grid.ColumnSpan="3"
BindingContext="{x:Reference Weight_Slider}"
Text="{Binding Value, StringFormat='Weight: {0:F0} kg'}"
TextColor="Black"
FontSize="22"
HorizontalOptions="Center"
VerticalOptions="Center"/>
<Slider Grid.Row="8"
Grid.ColumnSpan="3"
x:Name="Weight_Slider"
Maximum="400"
Minimum="35"
Value="70"/>
The label has a binding Text="{Binding Value, StringFormat='Weight: {0:F0} kg'}"
, is there any way to change it when the switch is activated?
namespace FitnessCalculatorApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class BMICalculatorPage : ContentPage
{
public BMICalculatorPage()
{
InitializeComponent();
}
void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
{
String WeightLabelText = Weight_Label.Text;
if (e.Value.Equals(false))
{
Weight_Slider.Maximum = 900;
Weight_Slider.Minimum = 75;
Weight_Slider.Value = 65;
Weight_Label.Text = "Weight: " + Weight_Slider.Value + " lbs";
}
}
}
}
UPDATE:
Try to create a viewmodel:
namespace FitnessCalculatorApp.Models
{
class BMICalculatorPageViewModel : INotifyPropertyChanged
{
string weight = string.Empty;
public string Weight
{
get => weight;
set
{
if (weight == value)
{
return;
}
onActivateSwitch(nameof(weight));
}
}
public event PropertyChangedEventHandler PropertyChanged;
void onActivateSwitch(string weight)
{
weight = "new weight";
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(weight));
}
}
}
And modify the binding of the weight tag:
<Label x:Name="Weight_Label"
Text="{Binding Weight}"/>
But I can't change the label text to "new weight" when activating the switch.