En aplicaciones .NET compiladas con Xamarin, MAUI, Avalonia UI y otros frameworks basados en MVVM, la vinculación de datos permite actualizar la Interfaz de Usuario cuando un objeto o colección subyacente cambia y viceversa.
Los objetos y colecciones de Realm están activos y se actualizan automáticamente para reflejar los cambios en los datos. Esto se debe a que los objetos de Realm implementan INotifyPropertyChangedLas colecciones de Realm implementan INotifyCollectionChanged. Al vincular colecciones y objetos activos a la interfaz de usuario (IU), tanto la IU como los objetos y colecciones activos se actualizan simultáneamente.
Data Binding Examples
The following code snippets show both the C# and XAML for three typical data-binding use cases. They all use the following Realm objects:
public partial class Employee : IRealmObject { [] [] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); [] public string EmployeeId { get; set; } [] public string Name { get; set; } [] public IList<Item> Items { get; } } public partial class Item : IRealmObject { [] [] public ObjectId Id { get; set; } = ObjectId.GenerateNewId(); [] public string OwnerId { get; set; } [] public string Summary { get; set; } [] public bool IsComplete { get; set; } }
Nota
Avoid Using ToList()
Debido a que las colecciones de Realm están activas, no debes llamar ToList() Al obtener una colección de objetos Realm, se fuerza la carga de la colección desde la memoria, por lo que la colección resultante deja de ser un objeto activo.
Binding to a Single Realm Object
En el siguiente ejemplo, creamos una propiedad pública de tipo Employee. En otra parte de nuestra clase, query nuestro realm para el Employee con un "EmployeeId" de "123":
public Employee Employee123 { get; } ... Employee123 = realm.All<Employee>() .FirstOrDefault(e => e.EmployeeId == "123");
In our XAML, we bind the Employee's Name property to a Label control's Text property:
<Label Text="{Binding Employee123.Name}"/>
Enlazando a una colección de Realm
There are two types of collections we can bind to. First, we can bind to a collection of Realm objects. In this code example, we create a public IEnumerable of the Employee Realm object and then populate that collection with all of the objects in the Employees collection:
public IEnumerable<Employee> Employees { get; } ... Employees = realm.All<Employee>();
En el archivo XAML relacionado, enlazamos un ListView a los Empleados IEnumerable para mostrar una lista de todos los Empleados. En este caso, estamos enumerando el valor "EmployeeId" de cada empleado:
<ListView x:Name="listAllEmployees" ItemsSource="{Binding Employees}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Label Text="{Binding EmployeeId}"/> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
También podemos enlazarnos a una propiedad de la colección de un objeto Realm. En este ejemplo, nos enlazamos a la propiedad Items de un Employee específico. La propiedad Items de la clase Employee es de tipo IList<Item>.
public Employee Employee123 { get; } ... IncompleteItems = Employee123.Items .AsRealmQueryable() .Where(i => i.IsComplete == false);
Nota
Note that we are calling the AsRealmQueryable() method. This is required because we are filtering the collection. If we want to list all of the Items in the Items collection, we do not need to call AsRealmQueryable().
The XAML implementation is similar to the example above:
<ListView x:Name="listIncompleteItems" ItemsSource="{Binding IncompleteItems}"> <ListView.ItemTemplate> <DataTemplate> <ViewCell> <Label Text="{Binding Summary}"/> </ViewCell> </DataTemplate> </ListView.ItemTemplate> </ListView>
Data Binding and MVVM
Al crear una aplicación .NET utilizando el patrón MVVM, a menudo se desea una correcta vinculación de datos en ambas direcciones entre la Vista y el ViewModel: si se cambia el valor de una propiedad en la interfaz de usuario, se debe notificar al ViewModel y viceversa. Los ViewModels suelen implementar la interfaz INotifyPropertyChange para garantizar esto.
Sin embargo, cuando vincula elementos de UI a un RealmObject, esta notificación ocurre automáticamente, lo que simplifica enormemente su código ViewModel.
You can also bind a UI element to a realm Live Query. For example, if you bind a ListView to a live query, then the list will update automatically when the results of the query change; you do not need to implement the INotifyPropertyChange interface.
For example, if you bind a ListView to a query that returns all Product objects, the list of available products updates automatically when a product is added, changed, or removed from the realm:
// Somewhere in your ViewModel AllProducts = realm.All<Products>();
<!-- Somewhere in your View --> <ListView ItemsSource="{Binding AllProducts}">