使用ObservableCollection <t>作为附加属性?</t>

时间:2014-04-30 07:21:49

标签: c# wpf

由于我不想为每个ObservableCollection创建一个不同的附加属性,其中T可以是我的任何个人逻辑类,我想知道是否可能更通用。

更具体地说,当使用DependencyProperty.RegisterAttached时,我希望所有者类型为ObservableCollection。

这可能吗?

1 个答案:

答案 0 :(得分:1)

您可以这样做,但是您需要为每种类型创建一个具体的类。这将解决您所说的问题 - 即

  

因为我不想为每个人创建不同的附加属性   的ObservableCollection,

这解决了这个问题(你只有一个附加属性)。但是你仍然需要一行来通过继承方式定义具体类型。

public class X<T>
{
    public static ObservableCollection<T> GetCollection(DependencyObject obj)
    {
        return (ObservableCollection<T>)obj.GetValue(CollectionProperty);
    }

    public static void SetCollection(DependencyObject obj, ObservableCollection<T> value)
    {
        obj.SetValue(CollectionProperty, value);
    }

    // Using a DependencyProperty as the backing store for Collection.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty CollectionProperty =
        DependencyProperty.RegisterAttached("Collection", typeof(ObservableCollection<T>), typeof(X<T>), new PropertyMetadata(null));


}

public class XInt : X<int> { }

然后在XAML中:

<Grid local:XInt.Collection="{Binding}">

</Grid>

如果你能够更清楚地解释你想要做什么(即为什么你需要附属物属于某种类型),那么可以有更好的解决方案。例如 - 为什么不将类型设置为IList,然后根据您需要的功能转换为IList或IEnumerable或INotifyCollectionChanged。