winforms - C++/CLI Winform - 是否可以有多个文本框的 1 个事件处理程序
问题描述
我试图通过使用我从另一篇文章中找到的这个函数来将用户输入限制为浮点数或整数。
private: System::Void keypressValidation(System::Windows::Forms::TextBox^ textBox, System::Windows::Forms::KeyPressEventArgs^ e) {
// Only allow 1 decimal point
if (e->KeyChar == '.')
{
if (textBox->Text->Contains(".") && !textBox->SelectedText->Contains("."))
{
e->Handled = true;
}
}
// Accepts only digits and Backspace keypress
else if (!Char::IsDigit(e->KeyChar) && e->KeyChar != 0x08)
{
e->Handled = true;
}
}
现在我的 UI 上有 8 个文本框,我为每个单独的文本框创建了 8 个不同的按键事件处理程序。
private: System::Void txtN3_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtN3, e);
}
private: System::Void txtN2_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtN2, e);
}
private: System::Void txtN1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtN1, e);
}
private: System::Void txtN0_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtN0, e);
}
private: System::Void txtD3_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtD3, e);
}
private: System::Void txtD2_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtD2, e);
}
private: System::Void txtD1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtD1, e);
}
private: System::Void txtD0_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e) {
keypressValidation(txtD0, e);
}
但后来在我的项目中,我将拥有大约 64 个文本框,我发现为每个文本框都设置一个事件处理程序太乏味了。有没有一种方法可以使它更紧凑,例如只有一个事件处理程序用于多个文本框?
解决方案
我的首选方法是遍历表单中的所有文本框并绑定单个事件处理程序。以下是 C++/CLI 中的示例代码:
private: System::Void Form1_Load(System::Object^ sender, System::EventArgs^ e)
{
for each (Control ^ ctrl in this->Controls)
{
if (ctrl->GetType() == TextBox::typeid)
{
ctrl->KeyPress += gcnew System::Windows::Forms::KeyPressEventHandler(this, &Form1::textBox1_KeyPress);
}
}
}
private: System::Void textBox1_KeyPress(System::Object^ sender, System::Windows::Forms::KeyPressEventArgs^ e)
{
}
推荐阅读
- gradle - Using FMPP with Gradle
- android - 使用 Volley 请求将图像作为 Multipart 发送
- node.js - Firefox 上的 Ice 连接失败消息,但适用于 Chrome
- python - 可执行蛇文件
- git - OSError: [Errno 95] 不支持操作
- azure-container-service - 当 AKS 删除分配给 LoadBalancer 类型服务的公共 IP 时?
- python - 在python中创建圆圈以掩盖图像并计算每个圆圈内的像素
- java - OnRetainCustomConfigurationInstance 之后所有 EditTexts 中的重复文本
- php - 带有 PHPSpec 的 PHP Composer 包中的文件结构
- asp.net - ASP.NET 网站更新程序集引用而不修改 .refresh 文件