SelectedIndexChanged在WinForms中运行时生成的控件不触发
本文关键字:控件 WinForms 运行时 SelectedIndexChanged | 更新日期: 2023-09-27 18:16:46
我的额头在这张桌子上撞破了。
我有一个表单,根据传递给它的参数生成一堆自定义UserControls (FieldMapper对象)。FieldMapper UserControl本质上只是几个标签,一个BindingSource和一个组合框(绑定到BindingSource)组织在一个TableLayoutPanel上。这个UserControl上的ComboBox被设置为DropDownList,并被绑定到BindingSource,该BindingSource使用在构造时作为参数传递的illist填充。
FieldMapper有一个名为MappingChanged的事件,每当底层SelectedIndexChanged事件被触发时,该事件就会被触发,并且一些逻辑决定了与事件一起触发的MappingChangedEventArgs的参数。这用于从其他组合框中删除/添加项目,以便在FieldMapping控件系列中没有任何内容可以被选中两次
问题是只有一个控件触发底层SelectedIndexChanged事件。这个控件是我首先改变的任何控件,它是ComboBox的选定值/索引。我选择哪一个并不重要,但只有该控件将触发后续事件,尽管其他控件的组合框已更改。下面是FieldMapper 的构造函数(删除了与问题无关的参数)
public FieldMapper(IList<string> fields)
{
InitializeComponent();
fields = fields.OrderBy(s => s).ToList();
string[] copyBuffer = new string[fields.Count + 1];
fields.CopyTo(copyBuffer, 1);
copyBuffer[0] = "NONE";
AvailableMappings = new BindingList<string>(copyBuffer.ToList());
AvailableMappings.RaiseListChangedEvents = true;
bindingSource = new BindingSource();
mapSelector.DataSource = bindingSource;
bindingSource.DataSource = AvailableMappings;
mapSelector.SelectedItem = "NONE";
mapSelector.SelectedIndexChanged += mapSelector_SelectedIndexChanged;
}
这些FieldMapper控件的父窗体生成它们如下:
private void BuildMappingTable(IEnumerable<string> fieldNames)
{
int row = 0;
foreach (var field in fbProject.Fields)
{
FieldMapper mapper = new FieldMapper(field.Key, field.Value.FieldName, fieldNames.ToList());
mapper.EnableMappingField = false;
mapper.Anchor = AnchorStyles.Right | AnchorStyles.Left;
mapper.MappingChanged += MappingChanged;
mappingTable.Controls.Add(mapper, 0, row);
row++;
}
if (!built && !original)
SetInitialValues()
built = true;
}
当我在调试这个问题时检查断点时,事件处理程序总是为FieldMapper和FieldMapper的comobobox的SelectedIndexChanged事件填充,所以我不确定为什么它们不触发。
编辑:按要求这里是mapSelector_SelectedIndexChanged方法
private void mapSelector_SelectedIndexChanged(object sender, EventArgs e)
{
if (currentValue == null || currentValue.Equals("NONE"))
{
currentValue = (string)mapSelector.SelectedItem;
OnMappingChanged(new MappingSelectedEventArgs(MappingSelectedEventArgs.MappingSelectedAction.SET, currentValue));
}
else if (mapSelector.SelectedItem.Equals("NONE"))
{
OnMappingChanged(new MappingSelectedEventArgs(MappingSelectedEventArgs.MappingSelectedAction.REMOVED, currentValue));
currentValue = "NONE";
}
else if (!mapSelector.SelectedItem.Equals(currentValue))
{
OnMappingChanged(new MappingSelectedEventArgs(MappingSelectedEventArgs.MappingSelectedAction.CHANGED, currentValue,
(string)mapSelector.SelectedItem));
currentValue = (string)mapSelector.SelectedItem;
}
}
protected void OnMappingChanged(MappingSelectedEventArgs args)
{
if (MappingChanged != null)
MappingChanged(this, args);
}
Replace:
private void mapSelector_SelectedIndexChanged(object sender, EventArgs e)
由:private void bindingSource_CurrentChanged(object sender, EventArgs e)