using System;
|
using System.Collections.Generic;
|
using System.Linq;
|
using System.Text;
|
using System.Threading.Tasks;
|
|
namespace LB_SmartVision.Forms.Pages
|
{
|
// 最优方案实现
|
public class ControlStateManager
|
{
|
private readonly Dictionary<string, Control> _controlMap = new Dictionary<string, Control>();
|
private readonly TableLayoutPanel _tablePanel;
|
|
public ControlStateManager(TableLayoutPanel tablePanel)
|
{
|
_tablePanel = tablePanel;
|
BuildControlMap();
|
}
|
|
// 初始化时构建控件字典(只需一次)
|
private void BuildControlMap(Control parent = null)
|
{
|
parent = parent ?? _tablePanel;
|
|
foreach (Control control in parent.Controls)
|
{
|
if (!string.IsNullOrEmpty(control.Name))
|
{
|
_controlMap[control.Name] = control;
|
}
|
|
if (control.HasChildren)
|
{
|
BuildControlMap(control);
|
}
|
}
|
}
|
|
// O(1) 快速访问
|
public T GetControl<T>(string name) where T : Control
|
{
|
return _controlMap.TryGetValue(name, out Control control) ? control as T : null;
|
}
|
|
// 获取TextBox值
|
public string GetTextBoxValue(string name)
|
{
|
return GetControl<TextBox>(name)?.Text;
|
}
|
|
// 获取CheckBox状态
|
public bool? GetCheckBoxState(string name)
|
{
|
return GetControl<CheckBox>(name)?.Checked;
|
}
|
|
/// <summary>
|
/// 获取 ComboBox 的选中项文本
|
/// </summary>
|
public string GetComboBoxText(string comboBoxName)
|
{
|
var comboBox = GetControl<ComboBox>(comboBoxName);
|
return comboBox?.SelectedItem?.ToString() ?? string.Empty;
|
}
|
|
/// <summary>
|
/// 获取 ComboBox 的选中索引
|
/// </summary>
|
public int GetComboBoxSelectedIndex(string comboBoxName)
|
{
|
var comboBox = GetControl<ComboBox>(comboBoxName);
|
return comboBox?.SelectedIndex ?? -1;
|
}
|
|
/// <summary>
|
/// 获取 ComboBox 的所有项
|
/// </summary>
|
public List<object> GetComboBoxItems(string comboBoxName)
|
{
|
var comboBox = GetControl<ComboBox>(comboBoxName);
|
return comboBox?.Items.Cast<object>().ToList() ?? new List<object>();
|
}
|
|
/// <summary>
|
/// 获取 ComboBox 的完整状态
|
/// </summary>
|
public ComboBoxState GetComboBoxState(string comboBoxName)
|
{
|
var comboBox = GetControl<ComboBox>(comboBoxName);
|
if (comboBox == null) return null;
|
|
return new ComboBoxState
|
{
|
Items = comboBox.Items.Cast<object>().ToList(),
|
SelectedIndex = comboBox.SelectedIndex,
|
SelectedItem = comboBox.SelectedItem,
|
Text = comboBox.Text
|
};
|
}
|
|
// 动态更新控件映射(当添加/删除控件时调用)
|
public void RefreshControlMap()
|
{
|
_controlMap.Clear();
|
BuildControlMap();
|
}
|
}
|
|
// ComboBox 状态数据结构
|
public class ComboBoxState
|
{
|
public List<object> Items { get; set; }
|
public int SelectedIndex { get; set; }
|
public object SelectedItem { get; set; }
|
public string Text { get; set; }
|
}
|
}
|