[英]C# Winforms Enable/Disable button based on function
I want a button on my winform to be enabled or disabled based on the return value of a particular function.我希望根据特定函数的返回值启用或禁用我的 winform 上的按钮。 Basically, I'm trying the following code in various places where the function will possible return a different value:
基本上,我在函数可能返回不同值的各个地方尝试以下代码:
btnNewNotices.Enabled = isSelectedPrinterValid();
this.btnNewNotices.Refresh()
However, this is not working.但是,这是行不通的。 Why is it when I call the refresh method after the enabled property is changed, that the button does not become enabled?
为什么在更改启用属性后调用刷新方法时,按钮未启用? I have to close the form and reopen it before the button properly disables.
在按钮正确禁用之前,我必须关闭表单并重新打开它。 What is the best way to accomplish what I need here without having to bounce the form?
在不必弹跳表单的情况下,在这里完成我需要的最佳方法是什么?
you can add a Databinding
for the Enabled
property.您可以为
Enabled
属性添加Databinding
。 if your method is implemented in your Form
then you can define a Property
如果您的方法在您的
Form
实现,那么您可以定义一个Property
public bool IsSelectedPrinterValid
{
get{ return this.isSelectedPrinterValid(); }
}
And add a Databinding as following:并添加如下数据绑定:
btnNewNotices.DataBindings.Add("Enabled", this, "IsSelectedPrinterValid");
You can refresh your value:您可以刷新您的值:
btnNewNotices.DataBindings[0].ReadValue();
The common way is to implement a ViewModel containing all Properties and Methods you need and bind your controls to these.常见的方法是实现一个包含所有你需要的属性和方法的 ViewModel,并将你的控件绑定到这些。
Short answer, but it's pretty straight forward.简短的回答,但它非常直接。
Using .Refresh();
使用
.Refresh();
causes the button to repaint itself, and resets the Enabled
property.导致按钮重新绘制自身,并重置
Enabled
属性。 There's no reason to use it in your context.没有理由在您的上下文中使用它。 Just remove it.
只需将其删除。
btnNewNotices.Enabled = isSelectedPrinterValid();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.