【问题标题】:Make Button Enabled after bools are true布尔值为真后使按钮启用
【发布时间】:2017-05-26 00:46:39
【问题描述】:

如果这三个布尔值为真,我需要激活按钮

public bool isFileOpened = false;
public bool isDrive = false;
public bool  isPrice = false;

它们在两个文本框被填充后变为真,并且 filePath 字符串不为空

private void textBox1_TextChanged(object sender, EventArgs e) {
    drive = CheckIntInput(sender, "not valid");
    if (drive != 0) {
        isDrive = true;
    }
}
private void textBox2_TextChanged(object sender, EventArgs e) {
    price = CheckIntInput(sender, "not valid");
    if (price != 0) {
        isPrice = true;
    }
}
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e) {
    filePath = openFileDialog1.FileName;
    label1.Text = filePath;
    isFileOpened = true;  
}

CheckIntInput 方法从文本框返回数字,如果不能将字符串转换为数字,则返回 0

以及我如何制作这样的东西:

if (isFileOpened && isDrive && isPrice) {
    showButton.Enabled = true;
}

我想在所有三个布尔值都为真后立即启用按钮,这三个字段可以用不同的方式输入,比如

  1. 文本框1
  2. 文本框2
  3. 打开文件对话框1

  1. 文本框1
  2. 打开文件对话框1
  3. 文本框2

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    有多种方法可以做到这一点,我会使用带有支持字段的属性,如下所示:

    public bool IsFileOpened
    {
        get { return _isFileOpened; }
        set
        {
            _isFileOpened = value;
            UpdateShowButton();
        }
    }
    
    public bool IsDrive
    {
        get { return _isDrive; }
        set
        {
            _isDrive = value;
            UpdateShowButton();
        }
    }
    
    public bool IsPrice
    {
        get { return _isPrice; }
        set
        {
            _isPrice = value;
            UpdateShowButton();
        }
    }
    
    private void UpdateShowButton()
    {
        if (IsPrice && IsDrive && IsFileOpened)
            showButton.Enabled = true;
    }
    private void textBox1_TextChanged(object sender, EventArgs e)
    {
        drive = CheckIntInput(sender, "not valid");
        if (drive != 0)
        {
            IsDrive = true;
        }
    }
    private void textBox2_TextChanged(object sender, EventArgs e)
    {
        price = CheckIntInput(sender, "not valid");
        if (price != 0)
        {
            IsPrice = true;
        }
    }
    private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
    {
        filePath = openFileDialog1.FileName;
        label1.Text = filePath;
        IsFileOpened = true;
    }
    

    实际上我也重命名了它,所以你必须使用带有大写首字母的属性。现在,每次更新属性时,它都会检查是否启用了 showButton。

    Here您可以阅读有关字段和属性的更多信息(以及支持字段)。

    【讨论】:

      猜你喜欢
      • 2012-04-19
      • 1970-01-01
      • 2020-12-14
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多