CollectionPropertiesShouldBeReadOnly和Dependency Properties

时间:2016-06-30 00:02:40

标签: c# xaml dependency-properties fxcop

我目前有一个依赖属性:

public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyPropertyDefaults", typeof(ICollection<string>), typeof(MyPanel), new PropertyMetadata(new List<string>()));

public ICollection<string> MyProperty
{
    get
    {
        return GetValue(MyPropertyProperty) as ICollection<string>;
    }

    set
    {
        this.SetValue(MyPropertyProperty, value);
    }
}

目标是该子面板将通过子面板操作的绑定传递一个列表,然后父节点可以稍后读取。 E.g。

 <xaml:MyPanel MyProperty="{Binding MyPropertyList}" />

但是,FxCop会报告CollectionPropertiesShouldBeReadOnly,我需要删除属性所需的setter。我该如何解决?做我正在做的事的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

像这样将setter声明为private:

public class MyPanel : Panel
{
    public static readonly DependencyProperty MyPropertyProperty = DependencyProperty.Register("MyPropertyDefaults", typeof(ICollection<string>), typeof(MyPanel), new PropertyMetadata(new List<string>()));

    public ICollection<string> MyProperty
    {
        get
        {
            return GetValue(MyPropertyProperty) as ICollection<string>;
        }

        private set
        {
            this.SetValue(MyPropertyProperty, value);
        }
    }
}