记录一些 WinForm 小功能的最佳代码实现,既是分享也是备忘。
如果你有更好的方案,欢迎留言讨论。
ComboBox 绑定带名称的简单数据
一般通过将数据填充到 Dictionary
Dictionary
代码段参考自 SOF。
private void PopulateComboBox(){var dict = new Dictionary<int, string>();dict.Add("Toronto", 2324);dict.Add("Vancouver", 64547);dict.Add("Foobar", 42329);comboBox1.DisplayMember = "Key";comboBox1.ValueMember = "Value";comboBox1.DataSource = new BindingSource(dict, null);}
匿名类
通过匿名类效果是差不多的:
var profiles = new[]{new {Name = "采集回波", Value = 0},new {Name = "计算回波", Value = 1},new {Name = "回波信号", Value = 2},new {Name = "逻辑曲线", Value = 3}};CboProfiles.DataSource = profiles;CboProfiles.DisplayMember = "Name";CboProfiles.ValueMember = "Value";
通过 OfType 筛选控件
WinForm 开发时经常有通过类型筛选控件的需求。
例如筛选出当前控件的子控件里面的所有 TextBox:
IEnumerable<TextBox> textboxs = parentControl.Controls.OfType<TextBox>();
