ComboBox、ListBox、CheckedListBox等列表型控件,可以单独为每个Item设置显示文本和数据。
为此,我们定义一个类,来实现这个Item的文本显示和数据关联:
public class ListComponentItem
{
private string _text = null;
private object _value = null;
public string Text { get => _text; set => _text = value; }
public object Value { get => _value; set => _value = value; }
public ListComponentItem(string text, object value = null)
{
Text = text;
Value = value;
}
public override string ToString()
{
return _text;
}
}
在使用时,只需初始化控件的Items即可:
foreach (var pFeatureLayer in lstPolygonFeatureLayer)
{
comboBoxPolygonLayer.Items.Add(new ListComponentItem(pFeatureLayer.Name, pFeatureLayer.FeatureClass));
}
或:
lstPolygonFeatureLayer.ForEach(e => comboBoxPolygonLayer.Items.Add(new ListComponentItem(e.Name, e.FeatureClass)));
那么,当我们选中某个Item时,通过如下方式取得其中的数据:
var pFeatureClass = (IFeatureClass)((ListComponentItem)comboBoxPolygonLayer.SelectedItem).Value;
本文介绍了一种自定义列表控件项的方法,通过创建一个类来实现ComboBox、ListBox等控件的Item文本显示和数据关联。这种方法允许为每个Item单独设置显示文本和关联数据,提高了控件的灵活性和实用性。

被折叠的 条评论
为什么被折叠?



