A
A
Anton2016-01-07 18:21:59
WPF
Anton, 2016-01-07 18:21:59

How to identify a ListBoxItem (WPF)?

Hello!
I hang a context menu on each ListBox element, in which there are certain options. I can easily get the SelectedIndex of each element when selecting an option from the context menu, but this is not enough for identification. Rather, it identifies the element relative to the given list.
But my list is formed from news that are in the database, which have their own unique ID. To me here just on it also it is necessary to identify all records.
From here I have two questions, each of which goes its own way.
1. Is it possible somehow to set the index manually when forming the list?
2. If the first option is not possible, is it possible to take out in the event handler (click on an element from the context menu) one or another value that was added to the list when it was formed?
I populate the list like this:

var lines = new List<NewsList>();

while (reader.Read())
{
    DateTime dateAdd = reader.GetDateTime(3);

    lines.Add(new NewsList() { ID = reader.GetInt32(0), Title = reader.GetString(1), Text = reader.GetString(2), DateAdd = dateAdd.ToString("d MMM yyyy, HH:mm") });
}

myListBox.DataContext = lines;

The NewsList itself looks like this:
public class NewsList
{
    public Int32 ID { get; set; }
    public String Title { get; set; }
    public String Text { get; set; }
    public String DateAdd { get; set; }
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton, 2016-01-08
@hummingbird

In general, he solved the problem.
Add ListBoxto SelectedValuePath="ID", where ID is what you need to receive in the handler in the future.
Next, to accept the ID, we write in the handler:
int newsID = (int)myListBox.SelectedValue;

M
MonkAlex, 2016-01-07
@MonkAlex

On the second question - of course you can. If you bind the "news" entity to a listbox element, then it can also be accessed by right clicking on it. If you create some kind of separate text for the listbox, then it is available in every way, but if you yourself did not write down the link to the news, you will have to get confused.
In general, without code it is difficult to understand what your problem is and what the question is.

M
MrDywar Pichugin, 2016-01-07
@Dywar

Nothing is clear either.
Do you need a unique Id for your list, or exactly the one that the news has in the database?
Or do you want the list to be displayed in order as in the database, sorted by the Id field? List.Sort

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question