簡體   English   中英

如何禁用按鈕,直到填寫所有字段

[英]How do I keep a button disabled untill all the fields are filled

我如何不斷檢查多個字段是否有輸入,並且一旦所有字段都有輸入啟用按鈕? 或者就像是一樣簡單

if( textbox1.text && textbox2.text && textbox3.text && ...){button1.isEnabled = true;}

是否有一個像團結一樣的更新方法來檢查更改?

您可以將所有文本框鏈接到同一個TextChanged事件,然后評估它們以查看是否所有文本框都已完成。

private void textBoxes_TextChanged(object sender, EventArgs e)
{
    EnableButton();
}


private void EnableButton()
{
    button1.Enabled = !Controls.OfType<TextBox>().Any(x => string.IsNullOrEmpty(x.Text));
}

你必須使用命令模式,它應該是這樣的 -

你的命令類 -

 public class RelayCommand : ICommand
    {
        private Action<object> _execute;
        private Func<object, bool> _canExecute;

        public RelayCommand(Action<object> execute, Func<object,bool> canExecute)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public void Execute(object parameter)
        {
            _execute(parameter);
        }

        public bool CanExecute(object parameter)
        {
            return _canExecute(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested += value;
                }
            }
            remove
            {
                if (_canExecute != null)
                {
                    CommandManager.RequerySuggested -= value;
                }
            }
        }
    }

你的按鈕代碼 -

<Button Content="Click Me" Command="{Binding ButtonCommand}"/>

你的命令屬性 -

public ICommand EnabledCommand { get; set; }

在你的構造函數中 -

ButtonCommand = new RelayCommand(ButtonCommandHandler, CanClick);

你的命令處理程序

private void ButtonCommandHandler(object obj)
    {
        // Do what ever you wanna
    }

你可以執行處理程序 -

 private bool CanClick(object arg)
    {
        return textbox1.Text.Trim().Length > 0 && textbox2.Text.Trim().Length > 0;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM