Xamarin形成绑定标签IsVisibleProperty

时间:2015-10-28 16:32:00

标签: c# xamarin xamarin.forms

我的登录页面有一个标签,当验证失败时,我会显示错误信息。当我绘制它时,我已将可见性设置为false。在我进行身份验证后,我想回到ContentPage并将标签设置为可见。它只是没有做任何我尝试将BindingMode枚举设置为TwoWay的东西,但它可以立即启用它然后我就无法将其关闭

在loginPage

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));
    }
}

1 个答案:

答案 0 :(得分:2)

使属性DisplayError公开,以便其他类可见。 如果仍然无法将绑定更改为:

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