将TextBlock的可见性绑定到TextBox

时间:2017-07-12 16:45:27

标签: c# wpf xaml mvvm

我尝试根据他们选择的用户名是否可用来绑定Visibility的{​​{1}}。这是TextBlock

的XAML
TextBlock

它绑定的属性,以及触发的命令是:

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

显示MessageBox但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 未显示。当我检查在Register方法中是否已经使用了用户名时,如何确保显示TextBlock

1 个答案:

答案 0 :(得分:4)

您必须阅读有关INotifyPropertyChanged的信息,实现此接口,然后将UsernameAvailable属性修改为:

private usernameAvailable

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

Here你可以找到INotifyPropertyChanged实现示例。