Dropdown list
Drop-down list is a control which shows the currently selected item and provides a dropdown list to select its current item. It is used to show a single selected item in a compact way.
Example
A dropdown list with two text items with the last one selected, could be created like so:
#![allow(unused)] fn main() { fn create_drop_down_list(ctx: &mut BuildContext) -> Handle<UiNode> { DropdownListBuilder::new(WidgetBuilder::new()) .with_items(vec![ TextBuilder::new(WidgetBuilder::new()) .with_text("Item 0") .build(ctx), TextBuilder::new(WidgetBuilder::new()) .with_text("Item 1") .build(ctx), ]) .with_selected(1) .build(ctx) } }
Keep in mind, that items of a dropdown list could be any widget, but usually each item is wrapped in some other widget that shows the current state of items (selected, hovered, clicked, etc.). One of the most convenient ways of doing this is to use Decorator widget:
#![allow(unused)] fn main() { fn make_item(text: &str, ctx: &mut BuildContext) -> Handle<UiNode> { DecoratorBuilder::new(BorderBuilder::new( WidgetBuilder::new().with_child( TextBuilder::new(WidgetBuilder::new()) .with_text(text) .build(ctx), ), )) .build(ctx) } fn create_drop_down_list_with_decorators(ctx: &mut BuildContext) -> Handle<UiNode> { DropdownListBuilder::new(WidgetBuilder::new()) .with_items(vec![make_item("Item 0", ctx), make_item("Item 1", ctx)]) .with_selected(1) .build(ctx) } }
Selection
Dropdown list supports two kinds of selection - None
or Some(index)
. To catch a moment when
selection changes, use the following code:
#![allow(unused)] fn main() { struct Foo { dropdown_list: Handle<UiNode>, } impl Foo { fn on_ui_message(&mut self, message: &UiMessage) { if let Some(DropdownListMessage::SelectionChanged(new_selection)) = message.data() { if message.destination() == self.dropdown_list && message.direction() == MessageDirection::FromWidget { // Do something. dbg!(new_selection); } } } } }
To change selection of a dropdown list, send DropdownListMessage::SelectionChanged
message
to it.
Items
To change current items of a dropdown list, create the items first and then send them to the
dropdown list using DropdownListMessage::Items
message.
Opening and Closing
A dropdown list could be opened and closed manually using DropdownListMessage::Open
and
DropdownListMessage::Close
messages.