在wpf自定义属性时,若此属性为集合类型的话,如下
public class DemoControl : Control { public List<string> Items { get { return (List<string>)GetValue(ItemsProperty); } } // Using a DependencyProperty as the backing store for Items. This enables animation, styling, binding, etc... public static readonly DependencyProperty ItemsProperty = DependencyProperty.Register("Items", typeof(List<string>), typeof(DemoControl), new UIPropertyMetadata(new List<string>())); }
使用情况
<local:DemoControl x:Name="demoControl1"> <local:DemoControl.Items> <sys:String>string1</sys:String> </local:DemoControl.Items> </local:DemoControl> <local:DemoControl> <local:DemoControl.Items> <sys:String>string2</sys:String> </local:DemoControl.Items> </local:DemoControl>
实际运行,Items属性的Count是2而不是1,这是因为其默认与所有实例共享.只需要在构造函数里初始化就可以了,设置为唯一的实例.
public DemoControl():base() { SetValue(ItemsProperty, new List<string>()); }msdn上有更详细的解释.