0

我正在创建一种行为,我需要允许将某些类型的列表设置为依赖属性。为了清楚起见,这里有一个例子:

<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 中传递的类型列表。我发现将类型集合传递给 a 的唯一方法DependencyProperty是使用 a 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); }
}

但是,这种方法的问题是集合永远不会重置。例如,如果我有两个UserControlsuse CustomBehaviorPropertyBList则 collection 将包含添加到两个 usercontrols 上的类型,这意味着它PropertyBList就像一个在所有使用此行为的 usercontrols 之间共享的静态集合。

如何解决这个问题呢?如何拥有一个List<Type>特定于用户控件实例而不是共享的依赖属性?

4

1 回答 1

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>());
}
于 2013-01-06T22:13:47.333 回答