WPF将项目添加到列表框(如果该项目尚不存在)

时间:2019-02-28 09:54:13

标签: c# wpf

我正在学习WPF,遇到了以下问题: 我有一个文本框(txbAuthor)和一个列表框(lstAuthors),我想做的是每当按下分号时,如果值不存在,我希望将txbAuthor中的值添加到lstAuthors中。我写了这段代码,但是没用:

private void Add_Author(object sender, KeyEventArgs e)
{
   if (e.Key == Key.P)
   {
   string Author = txbAuthor.Text.Remove(txbAuthor.Text.Length - 1);
   ListBoxItem itm = new ListBoxItem();
   itm.Content = Author;
   if (! lstAuthors.Items.Contains(itm))
   {
      lstAuthors.Items.Add(itm);
   }
      txbAuthor.Text = "";
  }
}

我也在这段代码中正在对KeyPress进行“ P”而不是分号的检查,因为我在“ Key”中找不到分号。选项,因此我也想知道如何检查分号而不是“ P”。

2 个答案:

答案 0 :(得分:1)

表达式

lstAuthors.Items.Contains(itm)

将始终为新创建的false对象返回itm。但这没关系,因为您的整个方法还是错误的。


在WPF应用程序中,通常将实现MVVM模式,并将ListBox的ItemsSource属性绑定到视图模型类中的字符串集合属性。

但是,第一步,您可以简单地在MainWindow类中声明一个ObservableCollection<string>成员,并在其构造函数中直接将其分配给ItemsSource属性:

private readonly ObservableCollection<string> authors
    = new ObservableCollection<string>();

public MainWindow()
{
    InitializeComponent();
    lstAuthors.ItemsSource = authors;
}

现在,您将只对该集合进行操作:

var author = txbAuthor.Text.TrimEnd(' ', ';');

if (!authors.Contains(author))
{
    authors.Add(author);
}

答案 1 :(得分:-1)

如果要检查是否按下了分号,应使用代码“ Keys.OemSemicolon”

在此处查看更多信息: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.keys?view=netframework-4.7.2

相关问题