行为<t> </t>中的集合类型的DependencyProperty

时间:2013-01-06 21:41:15

标签: wpf dependency-properties

我正在创建一个行为,我需要允许将某些类型的列表设置为依赖项属性。需要说明的是,这是一个例子:

<SomeUserControl .....>
  <i:Interaction.Behaviors>
    <local:CustomBehavior PropertyA="False">
      <local:CustomBehavior.PropertyBList>
        <x:Type Type="local:TypeA" />
        <x:Type Type="local:TypeB" />
        <x:Type Type="local:TypeC" />
      </local:CustomBehavior.PropertyBList>
    </local:CustomBehavior>
  </i:Interaction.Behaviors>
</SomeUserControl>

如您所见,行为需要接受在XAML中传递的类型列表。我发现将一组类型传递给DependencyProperty的唯一方法是使用DependencyPropertyKey

private static readonly DependencyPropertyKey PropertyBListPropertyKey =
    DependencyProperty.RegisterReadOnly("PropertyBList", typeof(List<Type>), typeof(CustomBehavior), new PropertyMetadata(new List<Type>()));

public static readonly DependencyProperty PropertyBListProperty = PropertyBListPropertyKey.DependencyProperty;

public List<Type> PropertyBList
{
    get { return (List<Type>)GetValue(PropertyBListProperty); }
}

然而,这种方法的问题是从不重置集合。例如,如果我有两个UserControls使用CustomBehavior,则PropertyBList集合将包含在两个用户控件上添加的类型,这意味着PropertyBList的行为类似于在两者之间共享的静态集合所有使用此行为的用户控件。

如何解决这个问题?如何将List<Type>的依赖项属性设置为特定于用户控件实例,而不是共享?

1 个答案:

答案 0 :(得分:1)

问题是您通过属性元数据中的默认值初始化PropertyBList值,该值由CustomBehavior的所有实例共享。您可以在CustomBehavior构造函数中初始化值:

private static readonly DependencyPropertyKey PropertyBListPropertyKey =
    DependencyProperty.RegisterReadOnly(
        "PropertyBList", typeof(List<Type>), typeof(CustomBehavior), null);

public static readonly DependencyProperty PropertyBListProperty =
    PropertyBListPropertyKey.DependencyProperty;

public List<Type> PropertyBList
{
    get { return (List<Type>)GetValue(PropertyBListProperty); }
}

public CustomBehavior()
{
    SetValue(PropertyBListPropertyKey, new List<Type>());
}