Свойство Custom ItemsSource для UserControl - программирование
Подтвердить что ты не робот

Свойство Custom ItemsSource для UserControl

Кто-нибудь знает, как создать пользовательский ItemsSource?

Что я хочу сделать, так это сделать ItemsSource для моего UserControl, чтобы он мог быть привязан к ObservableCollection<>.

Кроме того, я мог бы знать, когда обновляется количество элементов в ItemsSource, чтобы выполнять дополнительные процедуры.

Большое вам спасибо.

4b9b3361

Ответ 1

Возможно, вам понадобится сделать что-то подобное в своем управлении

public IEnumerable ItemsSource
{
    get { return (IEnumerable)GetValue(ItemsSourceProperty); }
    set { SetValue(ItemsSourceProperty, value); }
}

public static readonly DependencyProperty ItemsSourceProperty =
    DependencyProperty.Register("ItemsSource", typeof(IEnumerable), typeof(UserControl1), new PropertyMetadata(new PropertyChangedCallback(OnItemsSourcePropertyChanged)));

private static void OnItemsSourcePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
    var control = sender as UserControl1;
    if (control != null)
        control.OnItemsSourceChanged((IEnumerable)e.OldValue, (IEnumerable)e.NewValue);
}



private void OnItemsSourceChanged(IEnumerable oldValue, IEnumerable newValue)
{
    // Remove handler for oldValue.CollectionChanged
    var oldValueINotifyCollectionChanged = oldValue as INotifyCollectionChanged;

    if (null != oldValueINotifyCollectionChanged)
    {
        oldValueINotifyCollectionChanged.CollectionChanged -= new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
    }
    // Add handler for newValue.CollectionChanged (if possible)
    var newValueINotifyCollectionChanged = newValue as INotifyCollectionChanged;
    if (null != newValueINotifyCollectionChanged)
    {
        newValueINotifyCollectionChanged.CollectionChanged += new NotifyCollectionChangedEventHandler(newValueINotifyCollectionChanged_CollectionChanged);
    }

}

void newValueINotifyCollectionChanged_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    //Do your stuff here.
}

Ответ 2

Используйте элемент Items DependencyProperty ItemsSource в вашем CustomControl и затем привязывайтесь к этому DependencyProperty

Это XAML-код (распознает DataContext ListBox):

<UserControl
    x:Name="MyControl">
    <ListBox
        DataContext="{Binding ElementName=MyControl}"
        ItemsSource="{Binding ItemsSource}">
    </ListBox>
</UserControl>

Это CodeBehind:

public partial class MyCustomControl
{
    public IEnumerable ItemsSource
    {
        get { return (IEnumerable)GetValue(ItemsSourceProperty); }
        set { SetValue(ItemsSourceProperty, value); }
    }

    public static readonly DependencyProperty ItemsSourceProperty =
        DependencyProperty.Register("ItemsSource", typeof(IEnumerable),
            typeof(ToolboxElementView), new PropertyMetadata(null));
}

Это код, в котором вы используете свой "MyCustomControl":

<Window>
    <local:MyCustomControl
        ItemsSource="{Binding MyItemsIWantToBind}">
    </local:MyCustomControl>
</Window>