无法将类型“System.Collections.Generic.List”隐式转换为“System.Collectio

本文关键字:System 转换 Collectio Generic 类型 Collections List | 更新日期: 2023-09-27 18:34:27

>我正在尝试返回集合并将其分配给列表框,但出现以下错误

"无法将类型'System.Collections.Generic.List隐式转换为 'System.Collections.ObjectModel.ObservableCollection"

我是WPF和C#的新手,我不知道如何处理这个问题。

我只想将"我的视频"文件夹中的所有视频加载到包含媒体元素控件的列表框中。

正确的退货方式是什么?

法典:

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>

无法将类型“System.Collections.Generic.List”隐式转换为“System.Collectio

你的方法说它返回一个ObservableCollection<Video>但你返回一个List<Video>。创建一个ObservableCollection<Video>并返回它。

return new ObservableCollection<Video>(videoresult);

Multieple DataContexts:

上下文模型

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

主窗口

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

主窗口 Xaml

<ListBox x:Name="VideoList" ItemsSource="{ Binding Videos }" />
<ListBox x:Name="OtherListBox" ItemsSource="{ Binding OtherContext }" />

试试这个

ObservableCollection<Video> videoresult = new ObservableCollection<Video>();
return 语句中的

使用以下代码。

return (new ObservableCollection(videoresult));
您应该

更改返回类型,返回类型应该是 ObservableCollection 而不是 List。

相关文章: