列表项未清除

本文关键字:清除 列表 | 更新日期: 2023-09-27 18:29:18

我有一个表单,在其中显示另一个表单:

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块中再次显示代码后,列表中仍然有以前添加的新项目。为什么?

列表项未清除

this.ChannelTags = new List<string>();
this.ChannelTags.Clear();            
this.ChannelTags = channelTags;

我想用这个代码你是想复制channelTags吗?如果是这样,这就是如何做到的:

this.ChannelTags = channelTags.ToList();

您的代码只是创建一个空列表,清除它,然后丢弃它,并将channelTags分配给字段。