Button enable and disable on text changed event

后端 未结 3 1312
囚心锁ツ
囚心锁ツ 2020-12-22 09:42

I am wondering how I can set a button to disable if there is no text inside a text box, but when there is re enable it? Would I put it into a text changed event?

3条回答
  •  甜味超标
    2020-12-22 10:10

    You can do it in a more structured way using data binding and the little helper from here Exchange UserControls on a Form with data-binding

    static void Bind(Control target, string targetProperty, object source, string sourceProperty, Func expression)
    {
        var binding = new Binding(targetProperty, source, sourceProperty, true, DataSourceUpdateMode.Never);
        binding.Format += (sender, e) => e.Value = expression(e.Value);
        target.DataBindings.Add(binding);
    }
    

    Note that this is reusable piece of code that you can use in many scenarios. For your particular case, all you need is (after copying the code above) to put the following line in your form load event:

    Bind(button1, "Enabled", textBox1, "Text", value => !string.IsNullOrEmpty((string)value));
    

提交回复
热议问题