# Display and update collections

Version: 0.5.0
Framework commit: d503df2befa756e681fcdc6250e9552dc7388bea
Canonical URL: /docs/0.5.0/guides/collections/

Display a sequence of data either as children that follow a list in your state, or with an items control and a data template that describes one item. Avoid manually creating controls for every data object when the collection needs selection, sorting, or virtualization.

## Render a list in declarative Rust

In a component that runs again, repeat children with `for` and give each a stable key:

```rust
use ferroui_view::prelude::*;

#[derive(Clone, PartialEq)]
pub struct SearchResult {
    pub id: u32,
    pub name: String,
}

#[component(rerender)]
fn Results(results: Vec<SearchResult>) -> Element {
    rsx! {
        ListBox {
            for result in &results {
                ListBoxItem { key: result.id, content: result.name.clone() }
            }
        }
    }
}
```

The items of results that stay keep their controls when the list is filtered or reordered. In a view that runs once, `for_each(move || results.get(), |r: &SearchResult| r.id, |r: SearchResult| ..)` follows a signal of the list instead. For thousands of records, give a virtualizing `ListBox` an `items_source` and `item_template: template(|item: T| ..)`, whose items are components recycled as the list scrolls ([lists, async data & routing](/docs/0.5.0/declarative/patterns/)).

## Bind a list in XAML

This fragment uses explicit reflection bindings because it omits your application’s registered source types. See [compiled binding setup](/docs/0.5.0/xaml/compilation/#migrate-to-compiled-bindings-by-default) for typed XAML.

```xml
<ListBox xmlns="https://github.com/ferroui"
         ItemsSource="{ReflectionBinding Results}"
         SelectedItem="{ReflectionBinding SelectedResult, Mode=TwoWay}">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <TextBlock Text="{ReflectionBinding Name}" />
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>
```


## Add items from Rust

Inside an initialized application's view setup, a notifying collection can be connected directly to a list:

```rust
use std::rc::Rc;
use ferroui_controls::{ItemsSource, ListBox};
use ferroui_system::collections::object_model::ObservableCollection;

let names = ObservableCollection::<String>::new();
names.add("Ada".to_owned());
let list = ListBox::new();
list.set_items_source(Some(ItemsSource::new(Rc::new(names.clone()))));
names.add("Grace".to_owned());
```

Add `list` to the view. Both names should appear, including the item added after assigning the source. Cloning this collection shares its state; keep a handle in the model when later commands need to edit it.

For the templated XAML above, expose `Results` as an items source, `SelectedResult` as a writable notifying property, and `Name` on each item. The binding inside a data template sees the row's data context, so it reads the row's `Name` rather than a property on the whole screen.

## Collection and item notifications

Adding or removing a row requires a collection-change notification. Editing a property on an existing row requires that item's property-change notification. Replacing a plain Rust vector without notifying the bound property does neither automatically.

FerroUI's observable collections serve straightforward UI lists. DynamicData offers change sets and transformations for applications that filter, sort, and combine changing collections. Prefer a view-model projection over rebuilding the control tree from an unrelated event handler.

## Preserve identity and selection

Keep stable item identities while updating data. Replacing every item object can reset selection or expanded state even when the displayed text is unchanged. Explicitly define what selection means when filtering removes the selected item.

## Large data sets

Give a virtualized items control a bounded viewport. Wrapping it in an unconstrained outer scrolling container may defeat virtualization. Keep templates small, avoid synchronous I/O in getters, and measure scrolling with realistic data.

For hierarchical rows and columns, use the TreeDataGrid ecosystem guide; for a simple single selection, start with ListBox. [Choose a control](/docs/0.5.0/guides/choosing-controls/).

## Try the controls


This preview demonstrates selection with static items. The Rust collection example above adds model-driven updates in an application.

### Select an item

```xml
<ListBox xmlns="https://github.com/ferroui" SelectedIndex="1" Height="180">
  <ListBoxItem>Design</ListBoxItem>
  <ListBoxItem>Build</ListBoxItem>
  <ListBoxItem>Ship</ListBoxItem>
</ListBox>
```

```rust
use ferroui::prelude::*;
use ferroui::base::metadata::from_markup_value;
use ferroui::markup_xaml_loader::FerroRuntimeXamlLoader;

#[repr(C)]
pub struct App {
    base: Application,
}

ferro_class!(App: Application);
ferro_impl_classes!(App: FerroObjectImpl);

impl NewApplication for App {
    fn new_application() -> Ref<Self> {
        instantiate(Self { base: Application::construct() })
    }
}

impl ApplicationImpl for App {
    fn initialize(this: &Self) {
        Self::parent_initialize(this);
        ferroui::controls::register_types();
        FerroRuntimeXamlLoader::register();
        this.styles().add(FluentTheme::new().as_style());
    }

    fn on_framework_initialization_completed(this: &Self) {
        let lifetime = this.application_lifetime();
        if let Some(desktop) = lifetime.as_ref().and_then(|l| l.as_classic_desktop_style_application_lifetime()) {
            let value = FerroRuntimeXamlLoader::load(include_str!("View.xaml"), None, None, None, false)
                .expect("Example XAML should load");
            let view = from_markup_value::<Ref<Control>>(&Some(value)).expect("Example root must be a control");
            let window = Window::new();
            window.set_title(Some("FerroUI documentation example".to_owned()));
            window.set_width(560.0);
            window.set_height(420.0);
            window.set_padding(Thickness::uniform(24.0));
            window.set_content(Some(Control::boxed(view)));
            desktop.set_main_window(Some(window));
        }
        Self::parent_on_framework_initialization_completed(this);
    }
}

fn main() -> std::process::ExitCode {
    let args: Vec<String> = std::env::args().skip(1).collect();
    let result = AppBuilder::configure::<App>().use_platform_detect().start_with_classic_desktop_lifetime(&args);
    std::process::ExitCode::from(result as u8)
}

```

[Download the complete desktop project](/docs/0.5.0/generated/examples/list-box.zip). The browser preview runs real FerroUI controls with precompiled Rust support; this desktop application loads the same XAML.


## Public APIs and controls

- [`for_each`](/docs/0.5.0/api/ferroui-view/prelude/function-for_each/) and [`template`](/docs/0.5.0/api/ferroui-view/prelude/template/function-template/) — declarative lists and item components.
- [`ObservableCollection`](/docs/0.5.0/api/ferroui-system/collections/object_model/struct-observablecollection/) and [`ItemsSource`](/docs/0.5.0/api/ferroui-controls/struct-itemssource/) — source changes visible to controls.
- [`SourceCache`](/docs/0.5.0/api/ferroui-dynamic-data/cache/struct-sourcecache/) — keyed filtering and sorting; see the [DynamicData example](https://github.com/wieslawsoltes/FerroUI/blob/d503df2befa756e681fcdc6250e9552dc7388bea/samples/ReactiveUIExample/ViewModels/dynamic_data_view_model.rs).
- [ListBox](/docs/0.5.0/controls/reference/listbox/) — selection and item templates; [TreeDataGrid](/docs/0.5.0/controls/reference/treedatagrid/) for columns and hierarchy.
