Xamarin形成绑定标签IsVisibleProperty

本文关键字:标签 IsVisibleProperty 绑定 Xamarin | 更新日期: 2023-09-27 18:19:35

我的登录页面有一个标签,当身份验证失败时,我会显示一条错误消息。当我绘制它时,我已经将"可见性"设置为false。在我进行身份验证后,我想回到ContentPage并将标签设置为可见。它没有任何作用。我试过将BindingMode枚举设置为TwoWay,但这会立即启用它,然后我无法关闭

在登录页面中

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

在ViewModel页面

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

我的按钮在与上面相同的视图模型类中绑定到了这个,如果它没有通过简单的身份验证,它会尝试设置属性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);
}

OnPropertyChanged方法

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

Xamarin形成绑定标签IsVisibleProperty

将属性DisplayError设为公共属性,使其对其他类可见。当它仍然不起作用时,将绑定更改为:

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