.NET8でCommunityToolkit.Mvvmを使用したい
普通にインストールすると・・・
ObservableProperty属性をつけつと、以下のように書くよう促されます。
この書き方は.NET9 C#13以降でしか使えません。
[ObservableProperty] public partial string Text { get; set; }
.NET8の人はこっちの書き方しかできないようです。
partial class MyViewModel : ObservableObject { [ObservableProperty] private string name; [ObservableProperty] private bool isEnabled; }
MS Learnのページは.NET8時点の書き方で案内されています。
learn.microsoft.com
という話がObservablePropertyの定義に書いてありました。
/// <summary> /// An attribute that indicates that a given partial property should be implemented by the source generator. /// In order to use this attribute, the containing type has to inherit from <see cref="ObservableObject"/>, or it /// must be using <see cref="ObservableObjectAttribute"/> or <see cref="INotifyPropertyChangedAttribute"/>. /// If the containing type also implements the <see cref="INotifyPropertyChanging"/> (that is, if it either inherits from /// <see cref="ObservableObject"/> or is using <see cref="ObservableObjectAttribute"/>), then the generated code will /// also invoke <see cref="ObservableObject.OnPropertyChanging(PropertyChangingEventArgs)"/> to signal that event. /// <para> /// This attribute can be used as follows: /// <code> /// partial class MyViewModel : ObservableObject /// { /// [ObservableProperty] /// public partial string Name { get; set; } /// /// [ObservableProperty] /// public partial bool IsEnabled { get; set; } /// } /// </code> /// </para> /// And with this, code analogous to this will be generated: /// <code> /// partial class MyViewModel /// { /// public partial string Name /// { /// get => field; /// set => SetProperty(ref field, value); /// } /// /// public partial bool IsEnabled /// { /// get => field; /// set => SetProperty(ref field, value); /// } /// } /// </code> /// </summary> /// <remarks> /// <para> /// In order to use this attribute on partial properties, the .NET 9 SDK is required, and C# preview must /// be used. If that is not available, this attribute can be used to annotate fields instead, like so: /// <code> /// partial class MyViewModel : ObservableObject /// { /// [ObservableProperty] /// private string name; /// /// [ObservableProperty] /// private bool isEnabled; /// } /// </code> /// </para> /// <para> /// The generated properties will automatically use the <c>UpperCamelCase</c> format for their names, /// which will be derived from the field names. The generator can also recognize fields using either /// the <c>_lowerCamel</c> or <c>m_lowerCamel</c> naming scheme. Otherwise, the first character in the /// source field name will be converted to uppercase (eg. <c>isEnabled</c> to <c>IsEnabled</c>). /// </para> /// </remarks>