【问题标题】:How to Add multiple item in list Windows Phone如何在列表 Windows Phone 中添加多个项目
【发布时间】:2015-05-29 12:55:59
【问题描述】:

我正在使用 Windows Phone 应用程序,我想在已经存在的列表中添加项目我的问题是,当我添加第一个项目时它可以,但是当我添加第二个项目时,列表将替换我之前添加的项目

  private void btn_profession_Loaded(object sender, RoutedEventArgs e)
    {
        try
        {
            selectedKeywordsIds = App.skillIds;   // for selected keyword
            selectedProfName = App.professionalName;
            selectedProfId = App.professionalId;
            this.btn_profession.Content = selectedProfName;

             Key = App.skillKeywords  ;
             Pro = App.professionalName;
             final1=Key.Replace(Pro, "");


             List<string> numbers = final1.Split(',').ToList<string>();
             numbers.Add(selectedKeywordsIds);
             numbers = numbers.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();

             listBox1.ItemsSource = null;

             listBox1.ItemsSource = numbers;

    }

【问题讨论】:

  • 嗯,您使用的是 distinct,这意味着每个项目只会出现一次。
  • 所以在这里你只调用一次 add ......如果新添加的项目与列表中已经存在的项目相同,则“Distinct()”是一个问题。如果您第二次调用 add 在其他地方显示该位置。
  • 先生,当我添加第二个项目时,它将移至下一个索引
  • 啊,所以您的意思是在控件中显示时,新项目会替换先前添加的项目?也许你应该选择 numbers.Insert(0, newitem);那么你不是在集合的末尾追加而是在集合的开头?或者对集合或控件使用一些排序进行显示?

标签: c# windows-phone-8


【解决方案1】:

看起来您每次都在添加项目之前从某个先前的变量 final1 构建列表。你应该考虑这样的事情

final1 = string.Join(',', numbers.ToArray());

添加新项目后。因此,对“numbers”集合所做的更改将作为逗号分隔的项目存储在 final1 变量中。

【讨论】:

  • Przemysław Ładyński 先生,实际上我是从另一个页面获取值并将其存储在字符串值中,然后将其添加到列表中,但是当我添加第二个项目时,之前添加的项目将被我的项目替换跨度>
  • 你能显示你添加第二项的代码吗?我很确定您在此期间以某种方式覆盖了您的收藏。否则只需调用: numbers.Add(first); numbers.Add(秒);永远不要覆盖前一项。
【解决方案2】:

听起来您希望再次显示相同的列表项,这意味着您不应该在过滤空或空格后在 numbers 上使用 Distinct()

numbers  = numbers.Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

【讨论】:

    【解决方案3】:

    尝试使用 ObservableCollection-

    ObservableCollection<string> coll = new ObservableCollection<string>(numbers);
    

    将 ListBox 的 itemsource 设置为这个 observable 集合。

    你不需要使用-

    listBox1.ItemsSource = null;
    
    listBox1.ItemsSource = numbers;
    

    只需从可观察集合中添加或删除您想要的项目。更改将自动反映在 UI 中的 listBox1 上。

    另外,您可能需要更改代码 -

    numbers = numbers.Where(s => !string.IsNullOrWhiteSpace(s)).Distinct().ToList();
    

    到更适合可观察收集的东西。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多