wpf - 在 DataTemplate 中对绑定(bind)的 ItemsControl 进行排序(仅限 XAML)

标签 wpf sorting datatemplate itemscontrol collectionviewsource

是否有一种 XAML 唯一方法可以根据项目的属性之一自动对绑定(bind)项目(ViewModel 对象列表)ItemsControl 进行排序。 ItemsControl 是 DataTemplate 的一部分。我认为 CollectionViewSource 可以解决问题,但是如何将 CollectionViewSource 绑定(bind)到 ItemsControl。以下代码什么也没显示:

<--xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"-->
    <DataTemplate DataType="{x:Type vm:Company}">
        <DataTemplate.Resources>
            <CollectionViewSource x:Key="viewSource" Source="{Binding Employees}">
                <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="ID" />
                    </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>
        </DataTemplate.Resources>
        <Viewbox>
            <ItemsControl ItemsSource="{Binding Source={StaticResource viewSource}}">
                 <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal"/>
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
            </ItemsControl>
        </Viewbox>
    </DataTemplate>

最佳答案

尝试移动 CollectionViewSource Viewbox 范围内的资源而不是直接 DataTemplate :

<DataTemplate DataType="{x:Type vm:Company}">
    <Viewbox>
        <Viewbox.Resources>
            <CollectionViewSource x:Key="viewSource" Source="{Binding Employees}">
                <CollectionViewSource.SortDescriptions>
                        <scm:SortDescription PropertyName="ID" />
                    </CollectionViewSource.SortDescriptions>
            </CollectionViewSource>
        </Viewbox.Resources>
        <ItemsControl ItemsSource="{Binding Source={StaticResource viewSource}}">
             <ItemsControl.ItemsPanel>
                <ItemsPanelTemplate>
                    <StackPanel Orientation="Horizontal"/>
                </ItemsPanelTemplate>
            </ItemsControl.ItemsPanel>
        </ItemsControl>
    </Viewbox>
</DataTemplate>

关于wpf - 在 DataTemplate 中对绑定(bind)的 ItemsControl 进行排序(仅限 XAML),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1348028/

相关文章:

wpf - 绑定(bind)到 DataTemplate 中的 View 模型属性

c# - 获取点到几何体的距离

algorithm - 给定任意两个数字之间的二进制关系时对 n 个对象进行排序

Python 数学 - 类型错误 : 'NoneType' object is not subscriptable

WPF 绑定(bind)到 HierarchicalDataTemplate 内带有参数的方法

wpf - 在 ContentPresenter 中设置自动生成的 Textblock 样式

wpf - 从一个用户控件触发命令并在另一个用户控件的 View 模型中处理它

wpf - 如何忽略特定控件的默认样式?

.net - 是否有可以在 WPF 应用程序中使用的属性对话框控件?

c++ - 检查循环条件是否应该计入比较总数?