6

我有一个 UWP 项目想要读取 StorageFolder VideosLibrary 并在带有缩略图的视图中显示 mp4 文件列表。

使用 MVVM ligth 工具包,我用 xaml 设置了这 4 只苍蝇。Xaml 正在使用 UWP 社区工具包包装面板。

1)ViewModelLocator.cs

namespace UWP.ViewModels
{
/// <summary>
/// This class contains static reference to all the view models in the 
/// application and provides an entry point for the bindings.
/// </summary>

class ViewModelLocator
{
    /// <summary>
    /// Initializes a new instance of the ViewModelLocator class.
    /// </summary>
    public ViewModelLocator()
    {
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
        if (ViewModelBase.IsInDesignModeStatic)
        {
            // Create  design time view services and models
        }
        else
        {
            // Create run Time view services and models
        }
        //Register services used here

        SimpleIoc.Default.Register<VideoListModel>();
    }


    public VideoListModel VideoListModel
    {
        get { return ServiceLocator.Current.GetInstance<VideoListModel>(); 
    }
}
}

2) 视频列表项.cs

namespace UWP.Models
{
class VideoListItem : ViewModelBase
{
    public string VideoName { get; set; }
    public string Author { get; set; }
    public Uri Vid_url { get; set; }
    public BitmapImage Image { get; set; }

    public VideoListItem(string videoname,string author,Uri url, BitmapImage img)
    {
        this.VideoName = videoname;
        this.Author = author;
        this.Vid_url = url;
        this.Image = img;
    }
}
}

3) 视频列表模型.cs

namespace UWP.ViewModels
{
class VideoListModel : ViewModelBase
{
    public ObservableCollection<VideoListItem> VideoItems { get; set; }

    private VideoListItem videoItems;

    public VideoListModel()
    {

    }

    public async static Task<List<VideoListItem>> GetVideoItem()
    {
        List<VideoListItem> videoItems = new List<VideoListItem>();
        StorageFolder videos_folder = await KnownFolders.VideosLibrary.CreateFolderAsync("Videos");
        var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".mp4" });
        var videos = await videos_folder.CreateFileQueryWithOptions(queryOptions).GetFilesAsync();


        foreach (var video in videos)
        {
            //Debug.WriteLine(video.Name);
            //videoItems.Add(new VideoListItem());
            var bitmap = new BitmapImage();
            var thumbnail = await video.GetThumbnailAsync(ThumbnailMode.SingleItem);
            await bitmap.SetSourceAsync(thumbnail);
            videoItems.Add(new VideoListItem(video.DisplayName, "", new Uri(video.Path),bitmap));

        }

        //foreach(var video in videoItems)
        //{
        //    Debug.WriteLine("Name:{0} , Author:{1}, Uri:{2}, Bitmap:{3}", video.VideoName, video.Author, video.Vid_url, video.Image.UriSource);
        //}


        return videoItems;
    }


}
}

4) 视频.xml

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="using:UWP.Views"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:Controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
  x:Class="UWP.Views.Video"
  mc:Ignorable="d"
  NavigationCacheMode="Enabled"
  DataContext="{Binding Source={StaticResource ViewModelLocator},Path=VideoListModel}">
<!--NavigationCacheMode Enable for the page state save-->
<Page.Resources>
    <DataTemplate x:Key="VideoTemplate">
        <Grid Width="{Binding Width}"
              Height="{Binding Height}"
              Margin="2">
            <Image HorizontalAlignment="Center"
                   Stretch="UniformToFill"
                   Source="{Binding Image}" />
            <TextBlock Text="{Binding VideoName}"/>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Author" />
                <TextBlock Text="{Binding Author}" />
            </StackPanel>
        </Grid>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView Name="VideosListWrapPanal"
              ItemTemplate="{StaticResource VideoTemplate}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Controls:WrapPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ListView>

</Grid>
</Page>

我想在我的 VideoListModel 中为构造函数做类似下面的事情。

public async MainViewModel()
{
   VideoItems = new ObservableCollection<MainMenuItem>(await GetVideoItem());

}

如何以异步方式完成此初始化?为了获取缩略图,我创建了 GetVideoItem() 方法,但我找不到在构造函数中异步调用 GetVideoItem 的方法。有谁知道如何解决这个任务?

4

4 回答 4

5

简短的回答是:你不能创建一个 constructor async

但是有一些选项可以解决这个问题。这里有两个建议:

解决方案 1:ViewModel 生命周期

很多 MVVM 框架使用生命周期方法来解决这个问题。您可以添加一个ActivateAsync方法,在实例化ViewModel.

在您的示例中,这可以在您的 ViewModelLocator 中完成。

interface IActivate
{
    Task ActivateAsync();
}

// Call it like this:
(model as IActivate)?.ActivateAsync(); // this will work even if the model does not implement IActivate

解决方案 2:使用工厂

另一种选择是使用 afactory method创建ViewModel. 可以在聚合所有数据后factory method获取所有async数据并创建对象。

public static async Task<CustomViewModel> Create()
{
    var data = await FetchAsyncData();
    return new CustomViewModel(data);
}

例子:

这里有一个关于如何使用该activate模式的简短片段。

public class ViewModelLocator 
{
    // existing implementation goes here

    public async Task<TViewModel> Create<TViewodel>
    {
        var model = ServiceLocator.Current.GetInstance<TViewodel>(); 
        var activate = model as IActivate;
        if(activate != null)
            await activate.ActivateAsync();

        return model;
    }
}

现在工厂方法只返回一个完全激活的模型。这种模式的优点是创建者不需要知道它正在创建的模型。它检查模型是否需要激活并调用它。然后可以将所有激活逻辑放在ViewModel.

于 2017-09-12T07:54:03.870 回答
1

我建议使用异步任务通知程序,如我关于异步 MVVM 数据绑定的文章中所述。

例如,使用NotifyTask这个帮助库

public NotifyTask<List<VideoListItem>> VideoItems { get; }

public VideoListModel(IKnownFolderReader knownFolder)
{
  _knownFolder = knownFolder;
  VideoItems = NotifyTask.Create(() => _knownFolder.GetData());
}

然后,您的数据绑定将从 更改ItemsSource="{Binding VideoItems}"ItemsSource="{Binding VideoItems.Result}"。此外,VideoItems还有其他几个属性,例如IsNotCompleted和,IsFaulted以便您的数据绑定可以根据任务的状态显示/隐藏元素。

这种方法避免了微妙的问题Result问题ContinueWith

于 2017-09-15T16:40:11.117 回答
1

最后我得到了显示视频列表的方法!

错误地我没有设置ListView ItemSource!虽然它仍然有错误,Type not found in cache:UWP.Services.IKnownFolderReader但我认为当应用程序通过加载文件启动时它会消失。

这是我的最终代码。

1) 页面.xml

<Page xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="using:UWP.Views"
  xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
  xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
  xmlns:Controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
  x:Class="UWP.Views.Video"
  mc:Ignorable="d"
  NavigationCacheMode="Enabled"
  DataContext="{Binding Source={StaticResource ViewModelLocator},Path=VideoListModel}"
  Loaded="Page_Loaded">
<!--NavigationCacheMode Enable for the page state save-->
<Page.Resources>
    <DataTemplate x:Key="VideoTemplate">
        <Grid Width="{Binding Width}"
              Height="{Binding Height}"
              Margin="2">
            <Image HorizontalAlignment="Center"
                   Height="200"
                   Width="200"
                   Source="{Binding Image}" />
            <TextBlock Text="{Binding VideoName}"/>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="Author" />
                <TextBlock Text="{Binding Author}" />
            </StackPanel>
        </Grid>
    </DataTemplate>
</Page.Resources>

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <ListView Name="VideosListWrapPanal"
              ItemsSource="{Binding VideoItems}"
              ItemTemplate="{StaticResource VideoTemplate}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <Controls:WrapPanel Background="LightBlue"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ListView>

    <!--<StackPanel Orientation="Vertical"
                VerticalAlignment="Center"
                HorizontalAlignment="Center">
        <Viewbox MaxHeight="100"
                 MaxWidth="100">
            <SymbolIcon Symbol="Video" />
        </Viewbox>
        <TextBlock TextAlignment="Center"
                   Text="Home"
                   Margin="0,15,0,0" />

    </StackPanel>-->

</Grid>
</Page>

2) 型号

  public string VideoName { get; set; }
    public string Author { get; set; }
    public Uri Vid_url { get; set; }
    public BitmapImage Image { get; set; }

    public VideoListItem(string videoname,string author,Uri url, BitmapImage img)
    {
        this.VideoName = videoname;
        this.Author = author;
        this.Vid_url = url;
        this.Image = img;
    }

3) 视图模型

class VideoListModel : ViewModelBase
{
    private IKnownFolderReader _knownFolder;

    private ObservableCollection<VideoListItem> _videoItems;
    public ObservableCollection<VideoListItem> VideoItems
    {
        get { return _videoItems; }
        set { Set(ref _videoItems, value); RaisePropertyChanged(); }
    }



    private VideoListItem _selectedVideoItem;

    public VideoListItem SelectedVideoItem
    {
        get { return _selectedVideoItem; }
        set { Set(ref _selectedVideoItem, value);}
    }


    public VideoListModel(IKnownFolderReader knownFolder)
    {
        _knownFolder = knownFolder;
        var task = _knownFolder.GetData();
        task.ConfigureAwait(true).GetAwaiter().OnCompleted(() => {
            List<VideoListItem> items = task.Result;
            VideoItems = new ObservableCollection<VideoListItem>(items);
        });
    }



}

4) IKnownFolderReader.cs

public interface IKnownFolderReader
{
    Task<List<VideoListItem>> GetData();
}

5) VideoFilesReader.cs

public class VideoFilesReader : IKnownFolderReader
{
    private VideoListItem videoItems;
    public async Task<List<VideoListItem>> GetData()
    {
        List<VideoListItem> videoItems = new List<VideoListItem>();
        StorageFolder videos_folder = await KnownFolders.VideosLibrary.GetFolderAsync("Videos");
        var queryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".mp4" });
        var videos = await videos_folder.CreateFileQueryWithOptions(queryOptions).GetFilesAsync();


        foreach (var video in videos)
        {
            var bitmap = new BitmapImage();
            var thumbnail = await video.GetThumbnailAsync(ThumbnailMode.SingleItem);
            await bitmap.SetSourceAsync(thumbnail);
            videoItems.Add(new VideoListItem(video.DisplayName, "", new Uri(video.Path), bitmap));

        }

        return videoItems;
    }
}

小心查看部分!

为了从文件夹中进行异步读取,我了解到应该将服务与接口分开

谢谢大家的帮助!我应该更多地研究MVVM模式,MVVM轻工具包和UWP开发,以防止再次出现此类错误!

于 2017-09-12T13:33:00.773 回答
0

我有一个类似的问题,我做了这样的事情:

public MainViewModel()
{
GetVideoItem().ContinueWith(result=>{VideoItems = new ObservableCollection<MainMenuItem>(result)});


}

您还可以为此放置一个 loadingData 变量,让用户知道数据正在加载。

    public IsLoading{get;set}=true;
    public MainViewModel()
    {
    GetVideoItem().ContinueWith(result=>{VideoItems = new ObservableCollection<MainMenuItem>(result);
                                IsLoading=false;});
    }
于 2017-09-12T06:36:39.427 回答