2

我有一个自定义控件


    static CustomControl1()
    {
        DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new     FrameworkPropertyMetadata(typeof(CustomControl1)));
    }

    public List<string> MyProperty
    {
        get { return (List<string>)GetValue(MyPropertyProperty); }
        set { SetValue(MyPropertyProperty, value); }
    }
    public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(List<string>), 
                                                   typeof(CustomControl1), 
                                                   new UIPropertyMetadata(new List<string>()));        

当我在我的应用程序中使用多个CustomControl1并为每个MyProperty设置值时

  <StackPanel HorizontalAlignment="Left" Orientation="Vertical" VerticalAlignment="Top" Width="176">
        <local:CustomControl1>          
            <local:CustomControl1.MyProperty>
                <System:String>A</System:String>
                <System:String>B</System:String>
                <System:String>C</System:String>
                <System:String>D</System:String>
            </local:CustomControl1.MyProperty>          
        </local:CustomControl1>
        <local:CustomControl1>          
            <local:CustomControl1.MyProperty>
                <System:String>F</System:String>
                <System:String>E</System:String>                    
            </local:CustomControl1.MyProperty>          
        </local:CustomControl1>
    </StackPanel>

运行解决方案时,每个CustomControl1 和设计模式中显示的所有值仅显示最后一个 customcontrol1 的值。

所以看起来它们都共享相同的实例数据。

4

1 回答 1

0

为集合(列表、字典……)创建依赖属性时,始终在类的构造函数中重新初始化 DP。(否则,您将对所有实例使用相同的列表)

所以在你的情况下:

public CustomControl1()
{
    MyProperty = new List<string>();
}

并删除依赖属性的默认值中的值:

public static readonly DependencyProperty MyPropertyProperty =
        DependencyProperty.Register("MyProperty", typeof(List<string>), 
                                                   typeof(CustomControl1), 
                                                   new UIPropertyMetadata(null));        
于 2012-10-28T09:43:16.463 回答