项目控件 ItemsSource 懒加载

3
假设您正在创建类似于WPF中的ComboBox的自定义控件。作为项目的来源,您提供了IQueryable<T>(或任何类型的IEnumerable集合),但您不希望允许控件调用GetIterator()并对其进行迭代(一种惰性加载)。
假设您从此类继承(因为您希望获得该控件的所有功能):
System.Windows.Controls.Primitives.Selector

类。 选择器类继承自System.Windows.Controls.ItemsControl类,该类提供了一个众所周知的依赖属性ItemsSource。

public static readonly DependencyProperty ItemsSourceProperty = DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(ItemsControl), 
    new FrameworkPropertyMetadata(null, new PropertyChangedCallback(ItemsControl.OnItemsSourceChanged)));

private static void OnItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    ItemsControl control = (ItemsControl) d;
    IEnumerable oldValue = (IEnumerable) e.OldValue;
    IEnumerable newValue = (IEnumerable) e.NewValue;
    ItemValueStorageField.ClearValue(d);
    if ((e.NewValue == null) && !BindingOperations.IsDataBound(d, ItemsSourceProperty))
    {
        control.Items.ClearItemsSource();
    }
    else
    {
        control.Items.SetItemsSource(newValue); // PROBLEM
    }
    control.OnItemsSourceChanged(oldValue, newValue);
}

如果我看得正确,这是迭代的地方。
internal void SetItemsSource(IEnumerable value)
{
    if ((!this.IsUsingItemsSource && (this._internalView != null)) && (this._internalView.RawCount > 0))
    {
        throw new InvalidOperationException(SR.Get("CannotUseItemsSource"));
    }
    this._itemsSource = value;
    this._isUsingItemsSource = true;
    this.SetCollectionView(CollectionViewSource.GetDefaultCollectionView(this._itemsSource, this.ModelParent));
}

所以我决定覆盖 ItemsSourceProperty 的元数据,并将其指向自己的静态方法, 在这个方法中,我计划不调用 SetItemsSource(而是延迟它)。

你认为应该如何实现呢?

谢谢

1个回答

1
你最好的选择可能是添加一个新的依赖属性,比如类型为IEnumerable的DelayedItemsSource。然后在延迟之后将ItemsSource绑定到DelayedItemsSource。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接