I want to disable a button if there is no Internet connection - without waiting for any user interaction. So, for example, on the Login page the user has entered id and password which would enable the button. However, if the Internet connection is lost (before they click the button) then the button should be disabled.
I have a BaseViewModel and am using Xamarin Essentials:
public class BaseViewModel : INotifyPropertyChanged
{
public bool IsNotConnected
{
get => _isNotConnected;
set => SetProperty(ref _isNotConnected, value);
}
public BaseViewModel()
{
Connectivity.ConnectivityChanged += Connectivity_ConnectivityChanged;
IsNotConnected = Connectivity.NetworkAccess != NetworkAccess.Internet;
}
~BaseViewModel()
{
Connectivity.ConnectivityChanged -= Connectivity_ConnectivityChanged;
}
public void Connectivity_ConnectivityChanged(object sender, ConnectivityChangedEventArgs e)
{
IsNotConnected = e.NetworkAccess != NetworkAccess.Internet;
}
protected bool SetProperty<T>(ref T backingStore, T value,
[CallerMemberName] string propertyName = "",
Action onChanged = null)
{
if (EqualityComparer<T>.Default.Equals(backingStore, value))
return false;
backingStore = value;
onChanged?.Invoke();
OnPropertyChanged(propertyName);
return true;
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
var changed = PropertyChanged;
if (changed == null)
return;
changed.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
In LoginPageViewModel I have:
public string Password
{
get => _password;
set
{
if (value == _password) return;
User = new User { Username = Username, Password = value };
SetProperty(ref _password, value);
}
}
public string Username
{
get { return _username; }
set
{
if (value == _username) return;
User = new User { Username = value, Password = Password };
SetProperty(ref _username, value);
}
}
public LoginPageViewModel()
{
LoginCommand = new Command(async () => await LoginClicked(), LoginAllowed);
}
private bool LoginAllowed()
{
if (IsNotConnected)
return false;
if (User == null)
return false;
if (string.IsNullOrEmpty(User.Username) || string.IsNullOrEmpty(User.Password) || IsNotConnected)
return false;
return true;
}
So - this works if there is no Internet when the App starts / login page loads, it also works if Internet is lost while on the Login page and the user does something in the the username or password box, but how do I make the button disabled as soon as the loss of Internet is detected (and IsNotConnected is set)?
Also, more generally, I would like to be able to "tell" anything in the app that might be interested that the Internet connection status has changed so that "it" can react straight away, without requiring or waiting for user interaction.