使用数据绑定排序列表 Windows 通用 C#
Sort List with Databinding Windows Universal C#
我通过发送 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>
现在我想对这个列表进行排序。价格最高的列表项目应该排在第一位。我该怎么做?
我假设您将 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(); }
}
我在列表中调用.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);
}
鉴于您现在将列表实现为 ObservableCollection,现在对 列表结构的任何更改 都会引发通知以自动刷新视图 (UI)。
我通过发送 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>
现在我想对这个列表进行排序。价格最高的列表项目应该排在第一位。我该怎么做?
我假设您将 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(); }
}
我在列表中调用.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);
}
鉴于您现在将列表实现为 ObservableCollection,现在对 列表结构的任何更改 都会引发通知以自动刷新视图 (UI)。