Search code examples
c#xamlrandomlistboxwindows-store-apps

How do I Random all the items in the listbox?


I don't want to random number, I want to random all the items in the listbox in C# XAML Windows Store App??

Anyone have code for that or have any idea how to do that?

I have this code of listbox

<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 this is how i am adding songs/videos to the playlist listbox

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);
    }
}

Solution

  • Here is an example.

    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>
    

    Note that there is PlaylistItems binded to ListBox. It would be the best to manipulate the collection of items, which is binded to ListBox, instead of manipulating ListBox itself.

    C# code:

    First you should define that PlaylistItems collection.

    public ObservableCollection<string> PlaylistItems
    {
        get;
        set;
    }
    

    And to make it possible to bind it to the ListBox, it is necessary to set the DataContext of your control (window or whatever).

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;  // <--
    }
    

    Now let's initialize PlaylistItems collection and add few items.

    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);
    }
    

    You can call this method in the constructor.

    public MainWindow()
    {
        InitializeComponent();
        this.DataContext = this;
        InitializePlaylist(10); // <--
    }
    

    And finally shuffle functionality.

    public IEnumerable<string> ShuffleItems(IEnumerable<string> items)
    {
        var rnd = new Random();
        return items.OrderBy(item => rnd.Next()).ToList();
    }
    

    Use it in your button handler to repopulate PlaylistItems with randomized items.

    private void Shuffle_Click(object sender, RoutedEventArgs e)
    {
        var shuffledItems = ShuffleItems(PlaylistItems);
    
        PlaylistItems.Clear();
    
        foreach (var item in shuffledItems)
            PlaylistItems.Add(item);
    }