How to Bind to a Collection
Binding to a collection in Avalonia UI is an effective way to display dynamic data. This guide will demonstrate how to bind an ObservableCollection
to a control, like a ListBox
or ItemsControl
, to show a list of items.
Binding to a Simple ObservableCollection
For a start, consider you have an ObservableCollection<string>
and you want to bind it to a ListBox
to display a list of string items.
Here's an example ViewModel
with an ObservableCollection<string>
:
public class ViewModel : ObservableObject
{
private ObservableCollection<string> _items;
public ObservableCollection<string> Items
{
get { return _items; }
set { SetProperty(ref _items, value); }
}
public ViewModel()
{
Items = new ObservableCollection<string> { "Item 1", "Item 2", "Item 3" };
}
}
In your view, you can bind this ObservableCollection
to a ListBox
like so:
<ListBox ItemsSource="{Binding Items}"/>