如何对 TabControl 中的 TabItem 进行排序

发布于 2024-12-06 19:24:43 字数 1479 浏览 0 评论 0原文

我有一个带有 Order 属性的 Page 类型的集合,我将 TabControl 的 ItemsSource 属性设置为 ObservableCollection。每当我更改实体的 Order 属性时我需要做什么 相关的 TabItem 位于正确的位置。

WPF XAML:

<TabControl Grid.Row="1" ItemsSource="{Binding Pages.ListViewModels}" SelectedItem="{Binding Pages.Current}"  >
    <TabControl.ContentTemplate>
        <DataTemplate>
            <views:EditPageView />
        </DataTemplate>
    </TabControl.ContentTemplate>
    <TabControl.ItemTemplate>
        <DataTemplate>                                    
            <TextBlock Text="{Binding Header}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

C# 代码:

public class QuestionPageSection : INotifyPropertyChanged
{
    public virtual int Id { get; set; }
    public virtual string Header { get; set; }
    private int _Order;
    public virtual int Order
    {
        get
        {
            return _Order;
        }
        set
        {
            _Order = value;
            this.RaisePropertyChanged(() => this.Order , PropertyChanged);
        }
    }
    public event PropertyChangedEventHandler  PropertyChanged;
}

我想强制 TabControl 根据 Order 属性对 TabItems 进行排序。所以现在我有这些问题:

  • 有没有办法以声明方式做到这一点?
  • TabControl 有 SortColumn 属性吗?
  • TabItem 是否有 TabOrder 属性?
  • 是否有任何类型的集合可以侦听其子项以根据子项的属性自动对自身进行排序?

任何其他想法都会受到赞赏。

I have a collection of type Page with an Order property, I set ItemsSource property of a TabControl an ObservableCollection. What I need to whenever I changed the Order property of an Entity
the related TabItem go in the correct location.

WPF XAML :

<TabControl Grid.Row="1" ItemsSource="{Binding Pages.ListViewModels}" SelectedItem="{Binding Pages.Current}"  >
    <TabControl.ContentTemplate>
        <DataTemplate>
            <views:EditPageView />
        </DataTemplate>
    </TabControl.ContentTemplate>
    <TabControl.ItemTemplate>
        <DataTemplate>                                    
            <TextBlock Text="{Binding Header}"/>
        </DataTemplate>
    </TabControl.ItemTemplate>
</TabControl>

C# Codes:

public class QuestionPageSection : INotifyPropertyChanged
{
    public virtual int Id { get; set; }
    public virtual string Header { get; set; }
    private int _Order;
    public virtual int Order
    {
        get
        {
            return _Order;
        }
        set
        {
            _Order = value;
            this.RaisePropertyChanged(() => this.Order , PropertyChanged);
        }
    }
    public event PropertyChangedEventHandler  PropertyChanged;
}

I want to force TabControl to sort TabItems based on the Order property. So now I have these questoins:

  • Is there any way to do it declaratively?
  • Does TabControl have a SortColumn property?
  • Does TabItem have a TabOrder property?
  • Is there any type of collection that listen to its childs to automatically sort itself based on a property of childs??

Any other idea would be apperciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

一直在等你来 2024-12-13 19:24:44

您只需要对 TabControl 绑定的集合进行排序

我一直讨厌 ObservableCollection 没有内置 Sort 方法,所以我通常使用我自己的继承自 ObservableCollection 的自定义类

public class ObservableCollectionEx<T> : ObservableCollection<T>
{
    public ObservableCollectionEx() : base() { }
    public ObservableCollectionEx(List<T> l) : base(l) { }
    public ObservableCollectionEx(IEnumerable<T> l) : base(l) { }

    #region IndexOf

    /// <summary>
    /// Returns the index of the first object which meets the specified function
    /// </summary>
    /// <param name="keySelector">A bool function to compare each Item by</param>
    /// <returns>The index of the first Item which matches the function</returns>
    public int IndexOf(Func<T, bool> compareFunction)
    {
        return Items.IndexOf(Items.FirstOrDefault(compareFunction));
    }

    #endregion

    #region Sorting

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void Sort<TKey>(Func<T, TKey> keySelector)
    {
        InternalSort(Items.OrderBy(keySelector));
    }

    /// <summary>
    /// Sorts the items of the collection in descending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void SortDescending<TKey>(Func<T, TKey> keySelector)
    {
        InternalSort(Items.OrderByDescending(keySelector));
    }

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
    public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
    {
        InternalSort(Items.OrderBy(keySelector, comparer));
    }

    /// <summary>
    /// Moves the items of the collection so that their orders are the same as those of the items provided.
    /// </summary>
    /// <param name="sortedItems">An <see cref="IEnumerable{T}"/> to provide item orders.</param>
    private void InternalSort(IEnumerable<T> sortedItems)
    {
        var sortedItemsList = sortedItems.ToList();

        foreach (var item in sortedItemsList)
        {
            Move(IndexOf(item), sortedItemsList.IndexOf(item));
        }
    }

    #endregion
}

我可以这样使用它:

ListViewModels = GetListViewModels();
ListViewModels.Sort(p => p.Order);

You simply need to sort the collection that your TabControl is bound to

I've always hated the fact that ObservableCollection doesn't have a built-in Sort method, so I usually use my own custom class that inherits from ObservableCollection

public class ObservableCollectionEx<T> : ObservableCollection<T>
{
    public ObservableCollectionEx() : base() { }
    public ObservableCollectionEx(List<T> l) : base(l) { }
    public ObservableCollectionEx(IEnumerable<T> l) : base(l) { }

    #region IndexOf

    /// <summary>
    /// Returns the index of the first object which meets the specified function
    /// </summary>
    /// <param name="keySelector">A bool function to compare each Item by</param>
    /// <returns>The index of the first Item which matches the function</returns>
    public int IndexOf(Func<T, bool> compareFunction)
    {
        return Items.IndexOf(Items.FirstOrDefault(compareFunction));
    }

    #endregion

    #region Sorting

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void Sort<TKey>(Func<T, TKey> keySelector)
    {
        InternalSort(Items.OrderBy(keySelector));
    }

    /// <summary>
    /// Sorts the items of the collection in descending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void SortDescending<TKey>(Func<T, TKey> keySelector)
    {
        InternalSort(Items.OrderByDescending(keySelector));
    }

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
    public void Sort<TKey>(Func<T, TKey> keySelector, IComparer<TKey> comparer)
    {
        InternalSort(Items.OrderBy(keySelector, comparer));
    }

    /// <summary>
    /// Moves the items of the collection so that their orders are the same as those of the items provided.
    /// </summary>
    /// <param name="sortedItems">An <see cref="IEnumerable{T}"/> to provide item orders.</param>
    private void InternalSort(IEnumerable<T> sortedItems)
    {
        var sortedItemsList = sortedItems.ToList();

        foreach (var item in sortedItemsList)
        {
            Move(IndexOf(item), sortedItemsList.IndexOf(item));
        }
    }

    #endregion
}

I can use it like this:

ListViewModels = GetListViewModels();
ListViewModels.Sort(p => p.Order);
紫轩蝶泪 2024-12-13 19:24:44

您可以使用 CollectionViewSource 在 UI 端对 ObservableCollection 进行排序。以下是示例链接: http://msdn.microsoft.com/en-us /library/ms742542.aspx

You can sort you're ObservableCollection on the UI side by using CollectionViewSource. Here's a link with examples: http://msdn.microsoft.com/en-us/library/ms742542.aspx

凤舞天涯 2024-12-13 19:24:44

谢谢 Rachel,你的解决方案给了我线索,但你的解决方案仍然是一个答案,因为每当我更改 Order 属性时我都可以手动调用 Sort 方法,但我想让它自动执行。所以我最终得到了你的代码的动态版本。

基于 Rachel,我找到了这个解决方案。

public class ObservableCollectionEx<T> : ObservableCollection<T>
{
    public ObservableCollectionEx() : base() { }

    public ObservableCollectionEx(List<T> l) : base(l) { }

    public ObservableCollectionEx(IEnumerable<T> l) : base(l) { }

    Func<IEnumerable<T>,IEnumerable<T>> sortFunction;
    Action reset;

    #region IndexOf

    /// <summary>
    /// Returns the index of the first object which meets the specified function
    /// </summary>
    /// <param name="keySelector">A bool function to compare each Item by</param>
    /// <returns>The index of the first Item which matches the function</returns>
    public int IndexOf(Func<T , bool> compareFunction)
    {
        return Items.IndexOf(Items.FirstOrDefault(compareFunction));
    }

    #endregion IndexOf

    #region Sorting

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void SetSort<TKey>(Func<T , TKey> keySelector)
    {
        sortFunction = list => list.OrderBy(keySelector);
        InternalSort();
        reset = () => SetSort(keySelector);
    }

    /// <summary>
    /// Sorts the items of the collection in descending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void SetSortDescending<TKey>(Func<T , TKey> keySelector)
    {
        sortFunction = list => list.OrderByDescending(keySelector);
        InternalSort();
        reset = () => SetSortDescending(keySelector);
    }

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
    public void SetSort<TKey>(Func<T , TKey> keySelector , IComparer<TKey> comparer)
    {
        sortFunction = list => list.OrderBy(keySelector , comparer);
        InternalSort();
        reset = () => SetSort(keySelector , comparer);
    }

    /// <summary>
    /// Sorts the items of the collection in descending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
    public void SetSortDescending<TKey>(Func<T , TKey> keySelector , IComparer<TKey> comparer)
    {
        sortFunction = list => list.OrderByDescending(keySelector , comparer);
        InternalSort();
        reset = () => SetSortDescending(keySelector , comparer);
    }

    /// <summary>
    /// Moves the items of the collection so that their orders are the same as those of the items provided.
    /// </summary>
    private void InternalSort()
    {
        UpdateTracking(null , Items.ToList());
    }

    private void MoveItemToItsLocation(T item)
    {
        var sortListCache = sortFunction(Items).ToList();
        Move(IndexOf(item) , sortListCache.IndexOf(item));
    }

    #endregion Sorting

    public void UpdateTracking(IEnumerable<T> oldItems , IEnumerable<T> newItems)
    {
        if (sortFunction == null) return;

        PropertyChangedEventHandler changeTracker = (o , change) => { MoveItemToItsLocation((T)o); };
        Action<T> attachChangeTracker = o => o.ExecuteOnCast<INotifyPropertyChanged>(x => x.PropertyChanged += changeTracker);
        Action<T> detachChangeTracker = o => o.ExecuteOnCast<INotifyPropertyChanged>(x => x.PropertyChanged -= changeTracker);

        var greeting = new[] { attachChangeTracker , MoveItemToItsLocation };
        var farwell = new[] { detachChangeTracker };

        oldItems.ForEach(detachChangeTracker);
        newItems.ForEach(attachChangeTracker , MoveItemToItsLocation);
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnCollectionChanged(e);

        switch (e.Action) {
            case NotifyCollectionChangedAction.Add:
            case NotifyCollectionChangedAction.Remove:
            case NotifyCollectionChangedAction.Replace:
                UpdateTracking(e.OldItems.SafeGet(x => x.Cast<T>()) , e.NewItems.SafeGet(x => x.Cast<T>()));
                break;
            case NotifyCollectionChangedAction.Reset:
                UpdateTracking(Items.ToList() , null);
                if (reset != null)
                    reset();
                break;
            default:
                break;
        }
    }
}

我只做了一点更改,使其遵循基础集合中的更改,因此在对基础集合或基础集合中的任何元素进行任何更改后,它会自动对自身进行排序。

Thanks Rachel, your solution gave me the clue, but still your solution is an answer because I can manually call the Sort method whenever I change the Order property, but I wanted to make it automatic. So I end up with a dynamic version of your code.

Based on the Rachel I approached to this solution.

public class ObservableCollectionEx<T> : ObservableCollection<T>
{
    public ObservableCollectionEx() : base() { }

    public ObservableCollectionEx(List<T> l) : base(l) { }

    public ObservableCollectionEx(IEnumerable<T> l) : base(l) { }

    Func<IEnumerable<T>,IEnumerable<T>> sortFunction;
    Action reset;

    #region IndexOf

    /// <summary>
    /// Returns the index of the first object which meets the specified function
    /// </summary>
    /// <param name="keySelector">A bool function to compare each Item by</param>
    /// <returns>The index of the first Item which matches the function</returns>
    public int IndexOf(Func<T , bool> compareFunction)
    {
        return Items.IndexOf(Items.FirstOrDefault(compareFunction));
    }

    #endregion IndexOf

    #region Sorting

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void SetSort<TKey>(Func<T , TKey> keySelector)
    {
        sortFunction = list => list.OrderBy(keySelector);
        InternalSort();
        reset = () => SetSort(keySelector);
    }

    /// <summary>
    /// Sorts the items of the collection in descending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    public void SetSortDescending<TKey>(Func<T , TKey> keySelector)
    {
        sortFunction = list => list.OrderByDescending(keySelector);
        InternalSort();
        reset = () => SetSortDescending(keySelector);
    }

    /// <summary>
    /// Sorts the items of the collection in ascending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
    public void SetSort<TKey>(Func<T , TKey> keySelector , IComparer<TKey> comparer)
    {
        sortFunction = list => list.OrderBy(keySelector , comparer);
        InternalSort();
        reset = () => SetSort(keySelector , comparer);
    }

    /// <summary>
    /// Sorts the items of the collection in descending order according to a key.
    /// </summary>
    /// <typeparam name="TKey">The type of the key returned by <paramref name="keySelector"/>.</typeparam>
    /// <param name="keySelector">A function to extract a key from an item.</param>
    /// <param name="comparer">An <see cref="IComparer{T}"/> to compare keys.</param>
    public void SetSortDescending<TKey>(Func<T , TKey> keySelector , IComparer<TKey> comparer)
    {
        sortFunction = list => list.OrderByDescending(keySelector , comparer);
        InternalSort();
        reset = () => SetSortDescending(keySelector , comparer);
    }

    /// <summary>
    /// Moves the items of the collection so that their orders are the same as those of the items provided.
    /// </summary>
    private void InternalSort()
    {
        UpdateTracking(null , Items.ToList());
    }

    private void MoveItemToItsLocation(T item)
    {
        var sortListCache = sortFunction(Items).ToList();
        Move(IndexOf(item) , sortListCache.IndexOf(item));
    }

    #endregion Sorting

    public void UpdateTracking(IEnumerable<T> oldItems , IEnumerable<T> newItems)
    {
        if (sortFunction == null) return;

        PropertyChangedEventHandler changeTracker = (o , change) => { MoveItemToItsLocation((T)o); };
        Action<T> attachChangeTracker = o => o.ExecuteOnCast<INotifyPropertyChanged>(x => x.PropertyChanged += changeTracker);
        Action<T> detachChangeTracker = o => o.ExecuteOnCast<INotifyPropertyChanged>(x => x.PropertyChanged -= changeTracker);

        var greeting = new[] { attachChangeTracker , MoveItemToItsLocation };
        var farwell = new[] { detachChangeTracker };

        oldItems.ForEach(detachChangeTracker);
        newItems.ForEach(attachChangeTracker , MoveItemToItsLocation);
    }

    protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnCollectionChanged(e);

        switch (e.Action) {
            case NotifyCollectionChangedAction.Add:
            case NotifyCollectionChangedAction.Remove:
            case NotifyCollectionChangedAction.Replace:
                UpdateTracking(e.OldItems.SafeGet(x => x.Cast<T>()) , e.NewItems.SafeGet(x => x.Cast<T>()));
                break;
            case NotifyCollectionChangedAction.Reset:
                UpdateTracking(Items.ToList() , null);
                if (reset != null)
                    reset();
                break;
            default:
                break;
        }
    }
}

I only made a little change to make it follow the changes in the underlying collection, so it will sort itself automatically after any changes made to underlying collection or any element in the underlying collection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文