您正在创建一个自定义控件的图像,其行为类似于ComboBox
WPF 中的行为。作为您提供的项目的来源IQueryable<T>
(或任何类型的IEnumerable
集合),但您不想让控件调用GetIterator()
和迭代它(某种延迟加载)。
假设您继承自(因为您想要该控件的所有功能)
System.Windows.Controls.Primitives.Selector
班级。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
(而是延迟它)。
在你看来应该怎么做?
谢谢