C# 控件的一个实例与另一个实例共享属性?

C# 控件的一个实例与另一个实例共享属性?,c#,silverlight,xaml,custom-controls,C#,Silverlight,Xaml,Custom Controls,我创建了自己的工具栏。在工具栏内,我有用于显示自定义项的集合属性: public static readonly DependencyProperty CustomItemsProperty = DependencyProperty.Register("CustomItems", typeof(List<UIElement>), typeof(DitatToolbar), new PropertyMetadata(new List<UIElement&g

我创建了自己的工具栏。在工具栏内,我有用于显示自定义项的集合属性:

public static readonly DependencyProperty CustomItemsProperty =
            DependencyProperty.Register("CustomItems", typeof(List<UIElement>), typeof(DitatToolbar), new PropertyMetadata(new List<UIElement>()));

        public List<UIElement> CustomItems
        {
            get { return GetValue(CustomItemsProperty) as List<UIElement>; }
            set { this.SetValue(CustomItemsProperty, value); }
        }
我的问题是,出于某种原因,我应用程序中的所有工具栏(各种视图)都会看到我仅在一个视图中声明的自定义项。这显然造成了一些问题。我想知道我的代码有什么问题,
CustomItem
dependency属性对整个应用程序来说是静态的

回答

依赖项属性必须按如下方式声明:

public static readonly DependencyProperty CustomItemsProperty =
                DependencyProperty.Register("CustomItems", typeof(List<UIElement>), typeof(DitatToolbar), new PropertyMetadata(null));
公共静态只读从属属性CustomItemsProperty=
DependencyProperty.Register(“CustomItems”、typeof(List)、typeof(DiAttoolbar)、new PropertyMetadata(null));
我将此属性的初始化添加到构造函数中:

public DitatToolbar()
        {
            this.CustomItems = new List<UIElement>();

            this.DefaultStyleKey = typeof(DitatToolbar);
        }
public DitatToolbar()
{
this.CustomItems=新列表();
this.DefaultStyleKey=typeof(DITATOOLBAR);
}

它看起来像是您在typeMetadata参数中为属性指定的默认值(
新属性元数据(new List()
)是在所有实例中共享的-即,它们都将以相同的空列表开始。使用null作为默认值,而是在构造函数中为每个控件初始化一个空列表。

如果您从拥有自定义项的一个视图中注释掉该自定义项,它是否会从所有其他视图中消失?不是这样。现在其他视图得到例外运行时,我说这个UI元素是其他容器的子元素。宾果!非常感谢,就是这样(我用答案更新了我的帖子)(我可以投票,但由于某些原因它不会作为答案,稍后再试)
public static readonly DependencyProperty CustomItemsProperty =
                DependencyProperty.Register("CustomItems", typeof(List<UIElement>), typeof(DitatToolbar), new PropertyMetadata(null));
public DitatToolbar()
        {
            this.CustomItems = new List<UIElement>();

            this.DefaultStyleKey = typeof(DitatToolbar);
        }