Hacktoberfest 2026: những issue maintainer đã đánh dấu cho tháng Mười, đang mở và phù hợp người mới. Xem issue Hacktoberfest

Can Source Generators Further Simplify Synchronization in MVVM Community Toolkit

Đang mở
#1,058 0 bình luận 1 reaction 0 người được giao Xem trên GitHub

Chưa có ai nhận issue này.

Đánh giá

Độ khó
5/5
Thời gian dự kiến
Hơn một tuần
Mức phù hợp với người mới
25/100
Loại issue
Tính năng
Độ rõ ràng
Cần làm rõ
Mức độ hoạt động
Đình trệ
Công nghệ
csharp
Lĩnh vực
tooling

Hướng nghiên cứu

Không có tệp repository, bài kiểm thử hoặc điểm vào của generator nào được nêu tên. Hãy bắt đầu bằng việc xem xét hành vi hiện có của source generator ObservableProperty và các thuộc tính đồng bộ hóa được đề xuất, sau đó xác định liệu việc wiring khai báo được yêu cầu cho property và collection có khả thi hay không. Công việc được xem là hoàn tất khi có một API đã được thống nhất và hành vi đồng bộ hóa hai chiều được tạo tự động, bao gồm cả việc ngăn vòng lặp.

Do mô hình lập chỉ mục viết ra từ nội dung của issue.

Mô tả

feature request :mailbox_with_mail:
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 PropertyChanged and CollectionChanged.
  • Explicit initialization of properties and collections from the Model.
  • Repeated logic to update one side when the other changes, including an isSyncing flag 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 the Model class.
  • [SyncProperty("Name")] marks the name property for bidirectional synchronization with Model.Name.
  • [SyncCollection("Items")] marks the items collection for bidirectional synchronization with Model.Items.

The source generator could then:

  • Initialize name and items from the Model in the constructor.
  • Subscribe to PropertyChanged on the Model to update name.
  • Subscribe to CollectionChanged on both Model.Items and ViewModel.Items for two-way updates.
  • Generate the update logic with an isSyncing guard 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

Ngôn ngữ chính
C#
Star
3.8k
Fork
401
Chỉ số merge pull request
Không có pull request nào được merge trong 30 ngày

Chuẩn bị môi trường

Bắt đầu từ đâu

  1. Đọc hết issue, rồi đọc hướng dẫn đóng góp của dự án.
  2. Bình luận trên issue rằng bạn sẽ nhận — tránh hai người làm cùng một việc.
  3. Fork repository và làm thay đổi trên một nhánh.
  4. Mở pull request có tham chiếu số hiệu của issue.

Issue khác của CommunityToolkit/dotnet

Tất cả issue của CommunityToolkit/dotnet

Issue tương tự

Thêm issue về C#

Nhận issue mới trong hộp thư của bạn

Bản tóm tắt ngắn những issue GitHub phù hợp với người mới.