InitLipton InitLipton - 6 days ago 6
C# Question

Xamarin forms binding Label IsVisibleProperty

My login page has a label, that when authentication fails i'll display an error message. When i'm drawing it i have set the Visibility is set to false. After i authenticate i want to come back to the ContentPage and set the label to visible. It just doesn't do anything I've tried setting the BindingMode enum to TwoWay but that enables it straight away and then i cant turn it off

in the loginPage

Label errorMessage = new Label { IsVisible = false, Text = "Invalid credentials please try again", TextColor = Color.Red };
errorMessage.SetBinding(IsVisibleProperty, LoginViewModel.ErrorMessagePropertyName);


In the ViewModel page

public const string ErrorMessagePropertyName = "DisplayError";
private bool _displayError = false;
private bool DisplayError
{
get { return _displayError; }
set
{
if (value.Equals(_displayError)) return;

_displayError = value;
OnPropertyChanged();
}
}


My button is bound to this in the same view model class as above, If it doens't pass the simple authentication it tries to set property
DisplayError


protected async Task ExecuteLoginCommand()
{
string eventMessage= string.Format("Authenticating User:{0} on {1}", UserName, DateTime.UtcNow);
Logger.LogEvent(eventMessage);

if(UserName == "g" && Password.Length > 2)
{
Application.Current.Properties.Add(Constants.KEY_IS_AUTHENTICATED, true);

await _navigation.PopAsync();
}
else
{
DisplayError = true;
string message = string.Format("Invalid user tried to log into device at this time {0}",DateTime.Now);
Logger.LogEvent(message);
}

Debug.WriteLine(UserName);
Debug.WriteLine(Password);
}


The
OnPropertyChanged
method

protected virtual void OnPropertyChanged([CallerMemberName]string propertyName = null)
{
if (PropertyChanged != null)
{
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}

Answer

Make the property DisplayError public so it becomes visible to other classes. When it still doesn't work change the binding to:

 errorMessage.SetBinding(Label.IsVisibleProperty, LoginViewModel.ErrorMessagePropertyName); 
Comments