0

我有一个表格,其中我正在显示另一种表格:

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

4

1 回答 1

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

我认为您正在尝试使用此代码复制channelTags? 如果是这样,这是如何做到这一点:

this.ChannelTags = channelTags.ToList();

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

于 2013-08-27T04:29:59.800 回答