简体   繁体   中英

Binding Visibility of TextBlock to TextBox

I'm attempting to bind the Visibility of a TextBlock based on whether or not the Username they have chosen is available. Here is the XAML of the TextBlock :

<TextBlock Grid.Row="5" Text="* Username already taken" Visibility="{Binding UsernameAvailable, Converter={StaticResource BoolToVis}}" Margin="5"/>

The property it is bound to, and the command that is fired is:

public bool UsernameAvailable { get; set; }

#region RegisterCommand

private DelegateCommand _registerCommand;
public ICommand RegisterCommand
{
    get
    {
        _registerCommand = new DelegateCommand(param => Register());
        return _registerCommand;
    }
}

private void Register()
{
    if (IsPasswordValid())
    {
        var newUser = new User
        {
            FirstName = _firstName,
            LastName = _lastName,
            Username = _userName,
            Password = _password //TODO: Hashing of password
        };
        using (var context = new WorkstreamContext())
        {
            var users = context.Set<User>();
            users.Add(newUser);
            context.SaveChanges();
        }
    }
    else
    {
        UsernameAvailable = true; // TODO: Display TextBlock correctly
        MessageBox.Show("Failed"); // TODO: Correctly show messages displaying what is incorrect with details
    }
}

public bool IsPasswordValid()
{
    return FirstName != string.Empty &&
            LastName != string.Empty &&
            UserName != string.Empty &&
            Password.Any(char.IsUpper);
}

#endregion

The MessageBox is displayed however the TextBlock does not appear. How can I ensure that the TextBlock is displayed when I check if the Username is already taken in the Register method?

You have to read about INotifyPropertyChanged, implement this interface and then modify UsernameAvailable property to:

private usernameAvailable

public bool UsernameAvailable 
{ 
    get
    {
        return usernameAvailable;
    }
    set
    {
        if (usernameAvailable != value)
        {
            usernameAvailable = value;
            OnPropertyChanged(nameof(UsernameAvailable));
        }
    }
}

Here you can find INotifyPropertyChanged implementation example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM