CommunityToolkit / dotnet

.NET Community Toolkit is a collection of helpers and APIs that work for all .NET developers and are agnostic of any specific UI platform. The toolkit is maintained and published by Microsoft, and part of the .NET Foundation.
https://docs.microsoft.com/dotnet/communitytoolkit/?WT.mc_id=dotnet-0000-bramin
Other
2.8k stars 277 forks source link

Generated code tries to assign to a read only `ObservableCollection` #850

Closed karmeye closed 3 months ago

karmeye commented 3 months ago

Describe the bug

This code

[ObservableObject]
public partial class MyViewModel : ViewModel
{
  public ObservableCollection<DataType> SelectedItems { get;  } = [];
}

results in error:

CS0200 Property or indexer "cannot be assigned to" "it is read only"

in the owner of the MyViewModel:

private void UpdateTwoWay_5_ItemsSource()
{
    if (this.initialized)
    {
        if (this.dataRoot != null)
        {
            if (this.dataRoot.ViewModel != null)
            {
                if (this.dataRoot.ViewModel.MyViewModel!= null)
                {
                    // Error here
                    this.dataRoot.ViewModel.MyViewModel.SelectedItems = (global::System.Collections.ObjectModel.ObservableCollection<global::Abc>)this.obj5.ItemsSource;
                }
            }
        }
    }
}

Regression

No response

Steps to reproduce

1. Do the above.

I'm using NuGet package: CommunityToolkit.Mvvm 8.2.2

Expected behavior

As I understand it, with collections you don't use, e.g., a List marked with ObservableProperty, you just do it the standard way with an ObservableCollection, and therefore it is only assigned once. So it should work to not have a setter.

Screenshots

No response

IDE and version

VS 2022

IDE version

Microsoft Visual Studio Community 2022 (64-bit) - Current Version 17.9.2

Nuget packages

Nuget package version(s)

8.2.2

Additional context

Adding a setter seems to make everything work.

Help us help you

No, just wanted to report this

Sergio0694 commented 3 months ago

That code is generated by the XAML compiler, not by the MVVM Toolkit. The issue is it doesn't support init only properties.