我有一个表单,我在其中显示另一个表单:
if (headerText == "")
{
MhrtTemplateColumn objMhrtTemplateColumn =
new MhrtTemplateColumn("", lstUnusedChannelTags);
objMhrtTemplateColumn.ShowDialog();
}
else
{
MhrtTemplateColumn objMhrtTemplateColumn =
new MhrtTemplateColumn(ChannelDesc, lstUnusedChannelTags, CurrentTag);
objMhrtTemplateColumn.ShowDialog();
}
这些是重载的构造函数:
public MhrtTemplateColumn(string channelDescription, List<string> channelTags)
{
InitializeComponent();
this.ChannelDescription = channelDescription;
this.ChannelTags = new List<string>();
this.ChannelTags.Clear();
this.ChannelTags = channelTags;
}
public MhrtTemplateColumn(string channelDescription, List<string> channelTags, string CurrentChannelTag)
{
InitializeComponent();
this.ChannelDescription = channelDescription;
this.ChannelTags = new List<string>();
this.ChannelTags.Clear();
this.ChannelTags = channelTags;
this.CurrentChannelTag = CurrentChannelTag;
}
这是MhrtTemplateColumn的Window_Loaded事件:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
txtChannelDescription.Text = ChannelDescription;
if (CurrentChannelTag != null && CurrentChannelTag != "")
{
if(ChannelTags.Contains(CurrentChannelTag) == false)
ChannelTags.Add(CurrentChannelTag);
cmbChannelTag.ItemsSource = null;
cmbChannelTag.ItemsSource = ChannelTags;
cmbChannelTag.SelectedValue = CurrentChannelTag;
}
else
{
cmbChannelTag.ItemsSource = null;
cmbChannelTag.ItemsSource = ChannelTags;
cmbChannelTag.SelectedIndex = 0;
}
}
我的问题是当执行else块时,新项目会添加到列表中。关闭表单并使用if块中的代码再次显示该表单后,列表仍然具有先前添加的新项目。为什么呢?
答案 0 :(得分:1)
this.ChannelTags = new List<string>();
this.ChannelTags.Clear();
this.ChannelTags = channelTags;
我认为使用此代码您正试图复制channelTags
?如果是这样,这是如何做到的:
this.ChannelTags = channelTags.ToList();
您的代码只会创建一个空列表,清除它,然后将其抛弃并将channelTags
分配给该字段。