How to enable a button when a user types into a textbox

后端 未结 6 569
礼貌的吻别
礼貌的吻别 2020-12-25 15:06

What is the simplest way in WPF to enable a Button when the user types something into a TextBox?

6条回答
  •  不知归路
    2020-12-25 15:30

    Use the Simple Command

    
    
    

    Here is the sample code in the View Model

    public class MyViewModel : INotifyPropertyChanged
    {
        public ICommand ClearTextCommand { get; private set; }
    
        private string _titleText; 
        public string TitleText
        {
            get { return _titleText; }
            set
            {
                if (value == _titleText)
                    return;
    
                _titleText = value;
                this.OnPropertyChanged("TitleText");
            }
        }   
    
        public MyViewModel()
        {
            ClearTextCommand = new SimpleCommand
                {
                    ExecuteDelegate = x => TitleText="",
                    CanExecuteDelegate = x => TitleText.Length > 0
                };  
        }            
    
        public event PropertyChangedEventHandler PropertyChanged;
    
        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }     
    }
    

    For more information see Marlon Grechs SimpleCommand

    Also check out the MVVM Project Template/Toolkit from http://blogs.msdn.com/llobo/archive/2009/05/01/download-m-v-vm-project-template-toolkit.aspx. It uses the DelegateCommand for commanding and it should be a great starting template for any project.

提交回复
热议问题