排序列表与绑定Windows通用c#

本文关键字:通用 Windows 绑定 列表 排序 | 更新日期: 2023-09-27 18:05:53

我通过发送httprequest和检索json格式的文本得到一个列表。我创建了这个列表:

<ListBox Background="Red" ItemsSource="{Binding}" x:Name="Itemlist">
    <ListBox.ItemTemplate>
        <DataTemplate>
             <StackPanel Orientation="Horizontal">
                 <TextBlock Text="{Binding Price}"></TextBlock>
                 <TextBlock Text="{Binding InventoryItem.properties.name}" Foreground="Green"></TextBlock>
             </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

现在我要对这个列表排序。价格最高的列表应该排在第一位。我该怎么做呢?

排序列表与绑定Windows通用c#

我在列表上调用。sort()函数:

  test.Items.Sort();
 public class Item:IComparable<Item>
    {
        public InventoryItem InventoryItem { get; set; }
        public double Price { get; set; }
        public int CompareTo(Item other)
        {
            return this.Price.CompareTo(other.Price);
        }

您需要创建一个继承ObservableCollection的新列表:

public class MyItemsList:ObservableCollection<Item>
{
}

一旦你这样做了,你可以按照@matthias Herrmann向你展示的模式来排序列表。

MyItemsListInstance.Items.Sort();
 public class Item:IComparable<Item>
    {
        public InventoryItem InventoryItem { get; set; }
        public double Price { get; set; }
        public int CompareTo(Item other)
        {
            return this.Price.CompareTo(other.Price);
        }

考虑到你将List实现为ObservableCollection,现在对列表结构的任何更改将引发通知以自动刷新View (UI)。

我假设您正在将ItemList ListBox绑定到属性?(在示例中命名为ItemList)

在属性的getter中,您可以添加一个自定义转换来对从源列表对象传入的数据进行排序。

private List<Item> itemList = ///etc.
public List<Item> ItemList //binding to this
{
    public get { return itemList.OrderByDescending(x => x.price).ToList(); }
}