我不想随机编号,我想在C#XAML Windows Store App中随机选择列表框中的所有项目?
任何人都有代码或知道如何做到这一点?
我有这个列表框的代码
<ListBox Name="Playlist" Background="White" DoubleTapped="Playlist_DoubleTapped" KeyUp="Playlist_KeyUp"
Foreground="Black" SelectionMode="Single" SelectionChanged="Playlist_SelectionChanged"
ScrollViewer.VerticalScrollMode="Enabled"
ScrollViewer.VerticalScrollBarVisibility="Auto"
Grid.Column="0" Margin="28,82,1067,32">
@Baldrick这就是我将歌曲/视频添加到播放列表列表框的方式
public async void OpenFileButton_Click(object sender, RoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.ViewMode = PickerViewMode.List;
filePicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
filePicker.CommitButtonText = "Play";
foreach (string fileExtension in supportedAudioFormats)
{
filePicker.FileTypeFilter.Add(fileExtension);
}
foreach (string fileExtension in supportedVideoFormats)
{
filePicker.FileTypeFilter.Add(fileExtension);
}
IReadOnlyList<StorageFile> selectedFiles = await filePicker.PickMultipleFilesAsync();
if (selectedFiles.Count > 0)
{
foreach (StorageFile file in selectedFiles)
{
Playlist.Items.Add(file);
}
systemMediaControls.IsEnabled = true;
mediaSource.AutoPlay = true;
await SetNewMediaItem(0); // Start with first file in the list of picked files.
StorageFile files = Playlist.SelectedItem as StorageFile;
Thumbnail(files);
}
}
答案 0 :(得分:1)
这是一个例子。
XAML:
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<ListBox Grid.Row="0" Name="Playlist" ItemsSource="{Binding Path=PlaylistItems}"/>
<Button Grid.Row="1" Name="Shuffle" Content="Shuffle" Click="Shuffle_Click"/>
</Grid>
请注意PlaylistItems
绑定到ListBox
。最好操纵绑定到ListBox
的项目集合,而不是操纵ListBox
本身。
C#代码:
首先,您应该定义PlaylistItems
集合。
public ObservableCollection<string> PlaylistItems
{
get;
set;
}
为了能够将其绑定到ListBox
,有必要设置控件的DataContext
(窗口或其他)。
public MainWindow()
{
InitializeComponent();
this.DataContext = this; // <--
}
现在让我们初始化PlaylistItems
集合并添加一些项目。
public void InitializeItems(int count)
{
var items = new List<string>(count);
for (int i = 0; i < count; i++)
items.Add("Item " + i);
PlaylistItems = new ObservableCollection<string>(items);
}
您可以在构造函数中调用此方法。
public MainWindow()
{
InitializeComponent();
this.DataContext = this;
InitializePlaylist(10); // <--
}
最后改组功能。
public IEnumerable<string> ShuffleItems(IEnumerable<string> items)
{
var rnd = new Random();
return items.OrderBy(item => rnd.Next()).ToList();
}
在按钮处理程序中使用它来重新填充PlaylistItems
随机项目。
private void Shuffle_Click(object sender, RoutedEventArgs e)
{
var shuffledItems = ShuffleItems(PlaylistItems);
PlaylistItems.Clear();
foreach (var item in shuffledItems)
PlaylistItems.Add(item);
}