What is the best way to implement a DependencyProperty and also avoid 'CA2104: Do not declare read only mutable reference types'?

StackOverflow https://stackoverflow.com/questions/11042937

Domanda

What is the best way (or, is there a way) to implement a dependency property while avoiding the code analysis warning for CA2104 (Do not declare readonly mutable reference types)?

The MSDN documentation suggests this way of declaring your dependency property:

  public static readonly DependencyProperty StateProperty = DependencyProperty.Register(
    "State", typeof(Boolean), typeof(MyStateControl),new PropertyMetadata(false));

But that results in CA2104. It is easy enough to suppress, but I just wondered if there was a better way.

È stato utile?

Soluzione

That's a false positive; DependencyProperty is immutable.

You could use a property instead of a field, but you would then need to set it in a static constructor, triggering another warning.

Altri suggerimenti

EDIT: On further reflection I've decided that this warning sucks. The whole idea of the CA2104 is that you could get a hold of the pointer and use it to modify the contents of the object. Using the 'Get' operation on an additional property doesn't fix the underlying problem, it simply fools the Code Analysis into accepting the pattern. The proper way to handle this is to ignore the CA2104 in the properties of the project because it's a stupid warning to have in a world with public a DependencyProperty class.

This warning doesn't appear to be valid in Metro as DependencyProperties are immutable. However, it appears to be valid in WPF as you can add owners or mess with the metadata if you have a writable reference to the DependencyProperty. Here's the code and it isn't pretty, but this passes the FXCop guidelines.

    /// <summary>
    /// Identifies the Format dependency property.
    /// </summary>
    private static readonly DependencyProperty labelPropertyField = DependencyProperty.Register(
        "Label",
        typeof(String),
        typeof(MetadataLabel),
        new PropertyMetadata(String.Empty));

    /// <summary>
    /// Gets the LabelProperty DependencyProperty.
    /// </summary>
    public static DependencyProperty LabelProperty
    {
        get
        {
            return MetadataLabel.labelPropertyField;
        }
    }

    /// <summary>
    /// Gets or sets the format field used to display the <see cref="Guid"/>.
    /// </summary>
    public String Label
    {
        get
        {
            return this.GetValue(MetadataLabel.labelPropertyField) as String;
        }

        set
        {
            this.SetValue(MetadataLabel.labelPropertyField, value);
        }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top