| Severity | Error |
| Reported by | PostSharp.Patterns.Xaml |
| Message | [DependencyProperty] cannot be applied to <Target>: the target must be an instance property whose getter is not private. |
Cause
A dependency property stores one value for each instance of the class that declares it, and the DependencyPropertyAttribute aspect implements the getter and the setter of the target property by reading and writing this value. The aspect therefore requires an instance property whose getter is not private.
PostSharp reports XAM051 when the DependencyPropertyAttribute aspect is applied to:
- a static property;
- a property whose getter is private;
- a field, which C# allows because the aspect is a location-level aspect.
In the following example, the Phone property of ContactCard is static.
using System;
using System.Windows;
using PostSharp.Patterns.Xaml;
namespace Errors.XAM051_Error;
public class ContactCard : DependencyObject
{
// A dependency property stores a value per instance, so it cannot be static.
[DependencyProperty]
public static string? Phone { get; set; }
}
public static class Program
{
public static void Main()
{
ContactCard.Phone = "+1 555 0100";
Console.WriteLine( $"Phone: {ContactCard.Phone}" );
}
}
error XAM051: XAM051_Error.cs(11,27): [DependencyProperty] cannot be applied to Errors.XAM051_Error.ContactCard.Phone: the target must be an instance property whose getter is not private.
Resolution
- To store a value in each instance, remove the
staticmodifier, and make the getter public, protected or internal. - To define a property that you can set on objects of other classes, as
Grid.Column, use the AttachedPropertyAttribute aspect on a static property of type Attached<T> instead (see Attached Property). - For a field, turn the field into an auto-implemented property.
In the following example, Phone is an instance property, and each ContactCard stores its own phone number.
using System;
using System.Windows;
using PostSharp.Patterns.Xaml;
namespace Errors.XAM051_Fixed;
public class ContactCard : DependencyObject
{
// An instance property stores its value in each ContactCard.
[DependencyProperty]
public string? Phone { get; set; }
}
public static class Program
{
public static void Main()
{
var alice = new ContactCard { Phone = "+1 555 0100" };
var bob = new ContactCard { Phone = "+1 555 0199" };
Console.WriteLine( $"Phone of Alice: {alice.Phone}" );
Console.WriteLine( $"Phone of Bob: {bob.Phone}" );
}
}
Phone of Alice: +1 555 0100
Phone of Bob: +1 555 0199
See Also
Reference
DependencyPropertyAttribute
AttachedPropertyAttribute
Attached<T>
Other Resources