I have created a slider to know where is exactly is the point between 1-100, and now I want to change the color depending on the range, 0-50 green with a text "OK", 50-90 yellow with text "Careful", and above 90 red with text "Danger". But I can not even make it work with red color above 90.
MainPageViewModel.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
namespace App1
{
public class MainPageViewModel : INotifyPropertyChanged
{
private double slider;
public double Slider
{
get => slider;
set
{
slider = value;
OnPropertyChanged(nameof(Slider).ToString());
OnPropertyChanged(nameof(Color).ToString());
}
}
public string Color()
{
if (Slider > 90)
{
return "Red";
}
else return "Black";
}
public ICommand ResetCommand { get; set; }
public MainPageViewModel()
{
ResetCommand = new Command(Reset);
}
private void Reset()
{
Slider = double.MinValue;
}
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
and this is my
MainPage.xaml
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="App1.MainPage">
<StackLayout>
<Frame BackgroundColor="#2196F3" Padding="24" CornerRadius="0">
<Label HorizontalTextAlignment="Center"
Text="Title"
TextColor="White"
FontSize="36"/>
</Frame>
<Label HorizontalTextAlignment="Center"
Text="{Binding Slider}"
TextColor="{Binding Color}"
FontSize="36"/>
<Slider VerticalOptions="FillAndExpand"
Value="{Binding Slider}"
Maximum="100" />
<Button Text="Reset" Command="{Binding ResetCommand}"></Button>
</StackLayout>
</ContentPage>
Trying with Properties:
public Color mycolor;
public Color MyColor
{
get => mycolor;
set
{
mycolor = value;
{
if (Slider > 90)
{
OnColorChanged(Color.Red);
}
else OnColorChanged(Color.Yellow);
}
}
}
and
private void OnColorChanged(Color propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName.ToString()));
}