使用ObservableCollection<;T>;作为附属财产

本文关键字:财产 附属 ObservableCollection lt 使用 gt | 更新日期: 2023-09-27 18:00:57

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

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

这可能吗

使用ObservableCollection<;T>;作为附属财产

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

因为我不想为每个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(。