我有自定义控件
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的值。
所以看起来它们共享相同的实例数据。
答案 0 :(得分:0)
为集合创建依赖属性(List,Dictionary ...)时, 始终在类的构造函数 中重新初始化DP。 (否则,您将对所有实例使用相同的列表)
所以在你的情况下:
public CustomControl1()
{
MyProperty = new List<string>();
}
并删除Dependency Property的默认值中的值:
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(List<string>),
typeof(CustomControl1),
new UIPropertyMetadata(null));