How to disable button if textbox is empty in WPF

111 Views Asked by At

I'm using wpf.MVVMC to create a wpf page, it contains a textbox and a button. If the textbox is empty, the next button should be disabled. But it didn't work.

xaml:

<TextBox Name="ServerName" Text="{Binding ServerName}" TextChanged="SqlServerNameTextbox_TextChanged"/>
<Button Command="{Binding NextCommand}" IsEnabled="{Binding Path=IsButtonEnabled}">Next</Button>

ViewModel:

public bool isButtonEnabled = true;
public bool IsButtonEnabled
{
    get => isButtonEnabled;
    set
    {
        isButtonEnabled = value;
        OnPropertyChanged("IsButtonEnabled");

    }
}

public void HandleSqlNameTextChanged(string currentText)
{
    ServerName = currentText;
    if (string.IsNullOrEmpty(ServerName))
    {
        if (!NextCommand.CanExecute(null))
        {
            IsButtonEnabled = false;
        }
    }
}

public ICommand _nextCommand;
public virtual ICommand NextCommand
{
    get
    {

        if (_nextCommand == null)
        {

            _nextCommand = new DelegateCommand(
                () =>
                {
                    var controller = GetExactController();
                    controller.Next();
                },
                // can execute
                () => canGotoNext());
        }
        return _nextCommand;
    }
}

public virtual bool canGotoNext()
{
    if (!ValidateInputs())
    {
        IsButtonEnabled = false;
        return false;
    }
}

Do I miss anything? How to disable the button using command?
Thanks for your help.

Update: The mix use of change event and Command is not recommended by official. If this issue could be reopened, I will post the right answers.

0

There are 0 best solutions below