Game Development Reference
In-Depth Information
The next part is important, we need to add and update items as they are selected.
void listbox::Add(const std::wstring text)
{
listboxitemtext* item = new listboxitemtext(this, math::vector2(m_rectangle.Width(), m_font->GetLineSpacing()), text,
render::color::WHITE);
item->OnSelected() += [=] (void*, listboxitem* item) { UpdateList(item); };
if ( m_sorting == Descending )
{
m_items.push_back(item);
}
else
{
m_items.push_front(item);
}
Refresh();
}
Adding an item means creating a new item, and providing an event handler used when an
item becomes selected. Once constructed, depending on the selected sorting type for the
list box the item is either pushed to the back of the list or to the front. Finally we refresh
the control to ensure we compute the size of the control and the scrollbar.
The
OnSelected
handler is provided through a lambda function that calls
UpdateList
. This
handler checks if the item was selected or not and then adds it to the
m_selectedItems
list
or removes it from it. This ensures that the list of selected items is always perfectly in sync
with what is actually selected.
void listbox::UpdateList(listboxitem* item)
{
if ( item->Selected() )
m_selectedItems.push_back(item);
else
{
auto it = std::find(m_selectedItems.begin(), m_selectedItems.end(), item);
if ( it != m_selectedItems.end() )
{
m_selectedItems.erase(it);
}
}
}
Now that the inner workings of the listbox are complete, there are some usability details
thatwemustconsider.Thefirstis,sometimesitisdesirableforuserstoassociatesomekind