2017-07-03 86 views
1

我已经创建了一个声明了一个附加属性,这将持有的DataTemplates的集合类:WPF集合依赖项属性添加重复

public class DynamicTemplatesList : DependencyObject 
{ 
    public static readonly DependencyProperty TemplatesProperty = 
      DependencyProperty.RegisterAttached("Templates", typeof(TemplateCollection), typeof(DynamicTemplatesList), new FrameworkPropertyMetadata(new TemplateCollection(), 
    FrameworkPropertyMetadataOptions.None)); 

    public static void SetTemplates(UIElement element, TemplateCollection collection) 
     { 
      element.SetValue(TemplatesProperty, collection); 
     } 
} 

然后在XAML我设置的集合:

 <gfc:DynamicTemplatesList.Templates> 
      <gfc:Template Key="{StaticResource CheckBoxFieldType}" 
             DataTemplate="{StaticResource CheckBoxTemplate}" /> 
      <gfc:Template Key="{StaticResource LookupEditFieldType}" 
             DataTemplate="{StaticResource LookupEditTemplate}" /> 
      <gfc:Template Key="{StaticResource TextBoxFieldType}" 
             DataTemplate="{StaticResource TextBoxTemplate}" /> 
      <gfc:Template Key="{StaticResource DateEditFieldType}" 
             DataTemplate="{StaticResource DateEditTemplate}" /> 
     </gfc:DynamicTemplatesList.Templates> 

这似乎第一次正常工作。然而我注意到的一件事是,当我用这个依赖项属性关闭窗口,然后再次打开它时,看起来模板再次被添加到集合中。

第一次,就在收集4个模板,第二次8,等等等等。任何人都可以向我解释这里发生了什么?

我怀疑这是因为依赖属性的静态特性,为什么被复制的值,如果是这样的话任何人都可以点我的解决方案,以防止被安装集合属性从添加重复?

回答

0

的问题是,你设置new TemplateCollection()为依赖项属性的默认值。这个“静态”集合实例将在您使用您的属性而不用分配之前使用,就像您在XAML中一样。

你不应该使用别的比null用于保存一个修改集合依赖项属性的默认值。

public class DynamicTemplatesList 
{ 
    public static readonly DependencyProperty TemplatesProperty = 
     DependencyProperty.RegisterAttached(
      "Templates", 
      typeof(TemplateCollection), 
      typeof(DynamicTemplatesList)); 

    public static TemplateCollection GetTemplates(UIElement element) 
    { 
     return (TemplateCollection)element.GetValue(TemplatesProperty); 
    } 

    public static void SetTemplates(UIElement element, TemplateCollection collection) 
    { 
     element.SetValue(TemplatesProperty, collection); 
    } 
} 

现在明确地在XAML分配TemplateCollection情况是这样的:

<gfc:DynamicTemplatesList.Templates> 
    <gfc:TemplateCollection> 
     <gfc:Template ... /> 
     <gfc:Template ... /> 
     <gfc:Template ... /> 
     <gfc:Template ... /> 
    </gfc:TemplateCollection> 
</gfc:DynamicTemplatesList.Templates> 

作为一个说明,你的类不需要从DependencyObject派生如果只注册附加属性。

+0

看来,如果我将新的FrameworkPropertyMetadata(新TemplateCollection(), FrameworkPropertyMetadataOptions.None)的依赖项属性的默认值更改为null,当我加载相关的xaml控件时,它将引发一个空异常,指出Templates属性为null 。 –

+0

另一件事是,我不需要派生从DependencyObject有权访问SetCurrentValue方法? –

+0

是的,我确实改变了构造函数 –