Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot implicitly convert type 'System.Collections.Generic.List to 'System.Collections.ObjectModel.ObservableCollection

Tags:

c#

wpf

xaml

listbox

I am trying to return collection and assign it to a listbox but I am getting following error

"Cannot implicitly convert type 'System.Collections.Generic.List to 'System.Collections.ObjectModel.ObservableCollection"

I am new to WPF & C# I got no clue how to handle this.

All I want to do is load all videos in My Videos folder into listbox containing media element control.

What would be the correct way to return?

Code:

public class Video 
{
    public Uri SourceUri { get; set; }

    public static ObservableCollection<Video> LoadVideoInfo()
    {
        List<Video> videoresult = new List<Video>();

            foreach (string filename in
            System.IO.Directory.GetFiles(
            Environment.GetFolderPath(
            Environment.SpecialFolder.MyVideos)))

            videoresult.Add(new Video { SourceUri = new UriBuilder(filename).Uri });

        return videoresult;
    }
}

XAML:

<ListBox x:Name="VideoList" ItemsSource="{Binding }" Width="auto" Height=" auto" Margin="5,0,5,2" Grid.ColumnSpan="2" >
    <ListBox.ItemTemplate>
        <DataTemplate>
            <MediaElement Source="{Binding SourceUri}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
like image 794
Badrul Avatar asked Oct 24 '25 12:10

Badrul


1 Answers

Your method says it returns a ObservableCollection<Video> but you return a List<Video>. Create a ObservableCollection<Video> and return it.

return new ObservableCollection<Video>(videoresult);

Multieple DataContexts:

ContextModel

public class ContextModel
{
    public ObservableCollection<Video> Videos { get; set; }
    public object OtherContext { get; set; }
}

Main Window

this.DataContext = new ContextModel()
{
    Videos = Video.LoadVideoInfo(),
    OtherContext = LoadOtherContext()
};

Main Window Xaml

<ListBox x:Name="VideoList" ItemsSource="{ Binding Videos }" />
<ListBox x:Name="OtherListBox" ItemsSource="{ Binding OtherContext }" />
like image 103
SynerCoder Avatar answered Oct 27 '25 03:10

SynerCoder