我将MainPage中的ListBox绑定到使用CameraCaptureTask拍摄的图像集合。一切都正常,虽然我希望能够在检查我的SettingsPage中的各个RadioButtons时将排序顺序从升序更改为降序。我在IsolatedStorage中创建了一个值来记住检查哪个RadioButton,这样当我的应用程序的MainPage加载时,ListBox的绑定集合将被相应地排序和显示。然而,我的收藏品的实际分类是我遇到问题的地方。请注意,集合中的每个图像都会保存DateTaken
属性。
MainPage.xaml中
<ListBox x:Name="Recent" ItemsSource="{Binding Pictures}" Margin="8"
SelectionChanged="recent_SelectionChanged"
</ListBox>
现在,在我的构造函数中,我将DataContext
设置为PictureRepository.Instance
,实际上填充了来自IsolatedStorage的图像。在绑定之前,我不确定在何处或如何更改集合的排序顺序。我在想,实际上我可能想要绑定排序列表的副本,实际上不会更改IsolatedStorage中的排序顺序。我试图从Sorting Listbox Items by DateTime values
MainPage.xaml.cs中
public MainPage()
{
InitializeComponent();
DataContext = PictureRepository.Instance;
//Determine which Sort Radio Button has been Checked and display collection accordingly
//Also not sure if this should be performed in the OnNavigatedTo event
if (Settings.AscendingSort.Value)
{
//PictureRepository.Instance.Pictures.OrderBy(p => p.DateTaken).First();
//DataContext = PictureRepository.Instance;
var items = Recent.Items.Cast<CapturedPicture>().OrderBy(p => p.DateTaken).ToArray();
if (Recent.Items.Count != 0)
Recent.Items.Clear();
Recent.Items.Add(items);
}
else
{
//PictureRepository.Instance.Pictures.OrderByDescending(p => p.DateTaken).First();
//DataContext = PictureRepository.Instance;
var items = Recent.Items.Cast<CapturedPicture>().OrderByDescending(p => p.DateTaken).ToArray();
Recent.Items.Clear();
Recent.Items.Add(items);
}
}
这两个选项都没有用,虽然我从来没有尝试在填充ListBox之前对ObservableCollection进行排序。在学习这个概念时,我们将非常感谢任何链接,帮助或建议!
答案 0 :(得分:1)
我更喜欢在排序ListBox时使用CollectionViewSource。您可以允许控件处理此问题,而不是更改您绑定的后端集合。
您的页面xaml:
<phone:PhoneApplicationPage.Resources>
<CollectionViewSource x:Key="PicturesViewSource" Source="{Binding Pictures}">
<!-- Add for design time help. This object should return a collection of pictures
<d:Source>
<viewModels:MyFakeObject/>
</d:Source>
-->
</CollectionViewSource>
</phone:PhoneApplicationPage.Resources>
<Grid>
<ListBox ItemsSource="{Binding Source={StaticResource PicturesViewSource}}"/>
</Grid>
在您的页面中,您可以通过添加或删除SortDescriptions来修改ColletionViewSource的排序方式。每当用户更改单选按钮时,您都会这样做。
PicturesViewSource.SortDescriptions.Clear();
PicturesViewSource.SortDescriptions.Add(new SortDescription("DateTaken", ListSortDirection.Descending));