Can Source Generators Further Simplify Synchronization in MVVM Community Toolkit
Nadie ha tomado este issue todavía.
Evaluación
- Dificultad
- 5/5
- Tiempo estimado
- Más de una semana
- Aptitud para principiantes
- 25/100
Línea de trabajo
No se nombran archivos del repositorio, pruebas ni puntos de entrada del generador. Empieza revisando el comportamiento existente del generador de código fuente ObservableProperty y los atributos de sincronización propuestos; después, determina si es viable el cableado declarativo solicitado para propiedades y colecciones. Se considerará terminado cuando haya una API acordada y un comportamiento de sincronización bidireccional generado, incluida la prevención de bucles.
Escrito por el modelo de indexación a partir del texto del issue.
Descripción
Overview
I’m using the MVVM Community Toolkit to keep a ViewModel synchronized with a Model, handling both properties and collections. The [ObservableProperty] attribute already simplifies INotifyPropertyChanged implementation, but bidirectional synchronization between the ViewModel and Model still requires manually writing event handlers and update logic. This becomes repetitive and prone to errors, especially with multiple properties or collections.
Current Code:
Here’s my current ViewModel implementation, which synchronizes a Name property and an Items collection with a Model:
using CommunityToolkit.Mvvm.ComponentModel;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
public partial class ViewModel : ObservableObject
{
private readonly Model model;
private bool isSyncing = false;
[ObservableProperty]
private string name;
[ObservableProperty]
private ObservableCollection<string> items = new ObservableCollection<string>();
public ViewModel(Model model)
{
this.model = model;
// Initialize properties from the Model
Name = model.Name;
// Initialize the collection from the Model
foreach (var item in model.Items)
{
Items.Add(item);
}
// Sync properties: Update ViewModel when Model changes
model.PropertyChanged += (sender, e) =>
{
if (e.PropertyName == nameof(Model.Name))
{
Name = model.Name;
}
};
// Sync collections: Update ViewModel.Items when Model.Items changes
model.Items.CollectionChanged += (sender, e) =>
{
if (!isSyncing)
{
isSyncing = true;
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (string item in e.NewItems)
{
Items.Add(item);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (string item in e.OldItems)
{
Items.Remove(item);
}
}
isSyncing = false;
}
};
// Sync collections: Update Model.Items when ViewModel.Items changes
Items.CollectionChanged += (sender, e) =>
{
if (!isSyncing)
{
isSyncing = true;
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (string item in e.NewItems)
{
model.Items.Add(item);
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (string item in e.OldItems)
{
model.Items.Remove(item);
}
}
isSyncing = false;
}
};
}
// Sync properties: Update Model when ViewModel's Name changes
partial void OnNameChanged(string value)
{
model.Name = value;
}
}
Issue:
While functional, this code involves a lot of boilerplate:
- Manual event subscriptions for
PropertyChangedandCollectionChanged. - Explicit initialization of properties and collections from the Model.
- Repeated logic to update one side when the other changes, including an
isSyncingflag to avoid infinite loops.
Question:
Could the MVVM Community Toolkit leverage source generators to eliminate this boilerplate? I’d love to see a solution where synchronization is defined declaratively (e.g., via attributes), and the source generator handles all the event wiring and updates behind the scenes.
API breakdown
How It Could Work:
[SyncWithModel(typeof(Model))]specifies that this ViewModel synchronizes with theModelclass.[SyncProperty("Name")]marks thenameproperty for bidirectional synchronization withModel.Name.[SyncCollection("Items")]marks theitemscollection for bidirectional synchronization withModel.Items.
The source generator could then:
- Initialize
nameanditemsfrom the Model in the constructor. - Subscribe to
PropertyChangedon the Model to updatename. - Subscribe to
CollectionChangedon bothModel.ItemsandViewModel.Itemsfor two-way updates. - Generate the update logic with an
isSyncingguard to prevent infinite loops.
Usage example
Hypothetical Example:
Here’s what I envision the code could look like with source generators:
using CommunityToolkit.Mvvm.ComponentModel;
[SyncWithModel(typeof(Model))]
public partial class ViewModel : ObservableObject
{
private readonly Model model;
public ViewModel(Model model)
{
this.model = model;
}
[SyncProperty("Name")]
[ObservableProperty]
private string name;
[SyncCollection("Items")]
[ObservableProperty]
private ObservableCollection<string> items = new ObservableCollection<string>();
}
Breaking change?
No
Alternatives
None
Additional context
Would the MVVM Community Toolkit team consider adding this kind of source-generator-based synchronization? It would make the code much cleaner and more maintainable. If this is doable, what challenges might arise in implementing it? Alternatively, if there’s an existing way to achieve this with less boilerplate, I’d appreciate pointers or examples.
Help us help you
No, just wanted to propose this
- Lenguaje dominante
- C#
- Estrellas
- 3.8k
- Forks
- 401
- Métricas de merge de PR
- Sin PR fusionados en 30 d
Preparar el entorno
- Sin Dockerfile ni archivo de Docker Compose
- Tiene una plantilla de pull request
- Leer la guía de contribución
Primeros pasos
- Lee el issue completo y luego la guía de contribución del proyecto.
- Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
- Haz un fork del repositorio y trabaja en una rama.
- Abre un pull request que haga referencia al número del issue.
Más de CommunityToolkit/dotnet
-
bug :bug:
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
CommunityToolkit/dotnet#1206 ·
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 65/100
CommunityToolkit/dotnet#1186 ·
-
bug :bug:
Dificultad 1/5 Menos de una hora Aptitud para principiantes 68/100
CommunityToolkit/dotnet#648 ·
-
bug :bug:
Dificultad 3/5 1-2 días Aptitud para principiantes 68/100
CommunityToolkit/dotnet#1215 ·
-
feature request :mailbox_with_mail:
Dificultad 5/5 Más de una semana Aptitud para principiantes 45/100
CommunityToolkit/dotnet#1214 ·
Todos los issues de CommunityToolkit/dotnet
Issues similares
-
copilot documentation
Dificultad 1/5 1-3 horas Aptitud para principiantes 88/100
Los mantenedores suelen responder en 2 días
-
needs-triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
elsa-workflows/elsa-foundation#2290 ·
Los mantenedores suelen responder en 1 día
-
python triage
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
microsoft/semantic-kernel#14522 ·
Los mantenedores suelen responder en 4 días
-
area-integrations needs-area-label triage:bot-seen triage:needs-human
Dificultad 2/5 1-3 horas Aptitud para principiantes 84/100
microsoft/aspire#20652 · 1 comentario ·
Los mantenedores suelen responder en 1 día
-
Dificultad 2/5 1-3 horas Aptitud para principiantes 68/100
agoda-com/Shouldly.FromAssert#40 ·
Los mantenedores suelen responder en 1 día