如何在用户输入文本框时启用按钮?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (14)

当用户在TextBox中输入内容时,WPF中最简单的方法是启用Button吗?

提问于
用户回答回答于

使用命令

<TextBox Text={Binding Path=TitleText}/>

<Button Command="{Binding Path=ClearTextCommand}" Content="Clear Text"/>

以下是查看模型中的示例代码

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));
    }     
}

参阅 SimpleCommand

用户回答回答于

    <TextBox x:Name="TB"/>
    <Button IsEnabled="{Binding ElementName=TB,Path=Text.Length}">Test</Button>

扫码关注云+社区