I am learning WPF and I came across the following problem: I have one textbox (txbAuthor) and a listbox (lstAuthors), what I want to do is whenever semicolon is pressed I want the value in txbAuthor to be added in lstAuthors if the value doesn't already exist. I wrote this code, but it doesn't work:
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 = "";
}
}
Also I in this code the KeyPress is being checked on "P" instead of semicolon, because I couldn't find semicolon in "Key." options, so I would also like to know how to check on semicolon press instead of "P".
The expression
lstAuthors.Items.Contains(itm)
will always return false
for a newly created itm
object. But that doesn't matter, because your whole approach is wrong anyway.
In a WPF app you would usually implement the MVVM pattern and bind the ListBox's ItemsSource
property to a string collection property in a view model class.
However, as a first step you could simply declare an ObservableCollection<string>
member in your MainWindow class and in its constructor directly assign it to the ItemsSource property:
private readonly ObservableCollection<string> authors
= new ObservableCollection<string>();
public MainWindow()
{
InitializeComponent();
lstAuthors.ItemsSource = authors;
}
Now you would operate on that collection only:
var author = txbAuthor.Text.TrimEnd(' ', ';');
if (!authors.Contains(author))
{
authors.Add(author);
}
If you want to check if the semicolon is pressed you should use the code "Keys.OemSemicolon"
check more here: https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.keys?view=netframework-4.7.2
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.