c# - 如何引用父容器和子容器并对其执行操作
问题描述
说出你对 JavaScript 的要求,但导航层次结构是轻而易举的事。也许 C# 也是,但我不知道如何。我有一个带有一系列控件的程序,其中控件一遍又一遍地重复:
这些按钮的操作都是一样的,所以我重复了很多代码,而且似乎效率低下:
// There's a function just like this for EVERY button
private void FixedF1(bool isFixed)
{
if (isFixed)
{
F1FixerBtnDot.ForeColor = Color.FromArgb(80, 214, 0);
F1FixerBtnDot.TextAlign = ContentAlignment.TopLeft;
F1FixerBtnArea.BackgroundImage = Properties.Resources.green_btn_bk_sm;
F1FixerBtnBox.Text = "Fixed!";
PrefMatch("KillF1Help", "yes", F1FixerBtnDot);
}
else
{
F1FixerBtnDot.ForeColor = Color.FromArgb(244, 180, 0);
F1FixerBtnDot.TextAlign = ContentAlignment.TopRight;
F1FixerBtnArea.BackgroundImage = Properties.Resources.yellow_btn_bk_sm;
F1FixerBtnBox.Text = "Fix it!";
PrefMatch("KillF1Help", "no", F1FixerBtnDot);
}
}
private void F1FixerBtnDot_Click(object sender, EventArgs e)
{
if (regStuff.F1HelpActive())
{
// Save the new setting
prefs.SetPref("KillF1Help", "no");
// Toggle it
regStuff.RestoreF1();
FixedF1(false);
}
else
{
prefs.SetPref("KillF1Help", "yes");
regStuff.KillF1();
FixedF1(true);
}
}
在第一个函数中,我有代码可以“打开”和“关闭”按钮。每个按钮基本上都重复操作,我可能有 30 个或更多。我正在尝试重新编码它(基于我将如何在 JS 中执行此操作):
private void ToggleFixedButton(GroupBox which, bool isFixed, string prefName)
{
which.child(islabel).ForeColor = isFixed ? Color.FromArgb(80, 214, 0) : Color.FromArgb(244, 180, 0);
which.child(islabel).TextAlign = isFixed ? ContentAlignment.TopLeft : ContentAlignment.TopRight;
which.child(isPanel).BackgroundImage = isFixed ? Properties.Resources.green_btn_bk_sm : Properties.Resources.yellow_btn_bk_sm;
which.Text = isFixed ? "Fixed!" : "Fix it!";
PrefMatch("KillF1Help", isFixed ? "yes" : "no", which.child(islabel));
}
private void F1FixerBtnDot_Click(object sender, EventArgs e)
{
if (regStuff.F1HelpActive())
{
prefs.SetPref("KillF1Help", "no");
regStuff.RestoreF1();
ToggleFixedButton(sender.Parent, false, "KillF1Help");
}
else
{
prefs.SetPref("KillF1Help", "yes");
regStuff.KillF1();
ToggleFixedButton(sender.Parent, true, "KillF1Help");
}
}
最重要的是,假设我可以弄清楚如何向它发送访问表单元素所需的信息,我应该能够使用 ONE 来为 30 个控件执行相同操作的单独功能似乎并不聪明涉及。
解决方案
典型的 c# 方法是为您的自定义按钮创建一个自定义控件。
这样,您可以放置任何自定义逻辑来更改自定义控件中的颜色和其他属性。
可以使用is operator、.Controls和.OfType()的组合来遍历控件树并执行您想要的操作。但我不推荐它,因为它使您的按钮更难在其他控件中重用。
推荐阅读
- blazor - 在 Blazor 服务器端使用 CancellationTokenSource 实现去抖动
- reactjs - React-Select:保持编辑模式() 选择后(输入)
- autodesk-forge - 场景更新()与无效()
- c# - 什么是 C# 中的 SafeFileHandle,我应该什么时候使用它?
- git - 无法推送到 GitHub 上的远程存储库
- java - 如何解决“发生 JNI 错误,请检查您的安装。”
- r - 使用 gganimate 时 ggplot 的 geom_polygon 的奇怪行为
- php - 当在 CodeIgniter 中设置当前日期时,Bootstrap 日期选择器从视图中向 cotroller 发送空值
- c# - 在 Unity3D 中为 IL2Cpp 构建运行时代码编译是否有任何解决方案?
- angular - CLIENT_ERROR:主要来源的 S3 ARN 无效