ObservablePropertyAttribute Class
Definition
Important
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
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 ObservableObject, or it must be using ObservableObjectAttribute or INotifyPropertyChangedAttribute. If the containing type also implements the INotifyPropertyChanging (that is, if it either inherits from ObservableObject or is using ObservableObjectAttribute), then the generated code will also invoke OnPropertyChanging(PropertyChangingEventArgs) to signal that event.
This attribute can be used as follows:
partial class MyViewModel : ObservableObject
{
[ObservableProperty]
public partial string Name { get; set; }
[ObservableProperty]
public partial bool IsEnabled { get; set; }
}
And with this, code analogous to this will be generated:
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);
}
}
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)]
public sealed class ObservablePropertyAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)>]
type ObservablePropertyAttribute = class
inherit Attribute
Public NotInheritable Class ObservablePropertyAttribute
Inherits Attribute
- Inheritance
-
ObservablePropertyAttribute
- Attributes
Remarks
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:
partial class MyViewModel : ObservableObject
{
[ObservableProperty]
private string name;
[ObservableProperty]
private bool isEnabled;
}
The generated properties will automatically use the UpperCamelCase
format for their names, which will be derived from the field names. The generator can also recognize fields using either the _lowerCamel
or m_lowerCamel
naming scheme. Otherwise, the first character in the source field name will be converted to uppercase (eg. isEnabled
to IsEnabled
).
Constructors
ObservablePropertyAttribute() |