[UWP] MediaElement和MVVM [英] [UWP]MediaElement and MVVM

查看:62
本文介绍了[UWP] MediaElement和MVVM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用
MediaElement
是一个MVVM设计模式应用程序。从这个意义上讲,我无权访问XAML对象,但我可以为数据源提供绑定。  MediaElement需要
IRandomAccessStreamWithContentType 我提供的文件类型。请注意Source是一个属性,如果我想设置Source
是一个函数SetSource。如果你看第78行(
MainPageViewModel.cs )应用程序工作,我提供了所需的文件
并调用了函数,这不是MVVM设计。如果您评论该行并取消注释第79行,它将无效。我们怎样才能解决MVVM这个问题呢?

I am using MediaElement which is an MVVM design pattern application. In that sense, I don’t have access to XAML objects, but I can provide Binding to the data source. The MediaElement needs the IRandomAccessStreamWithContentType type of file which I provided. Please note Source is a property where if I want to setup Source is a function SetSource. If you look line 78 (MainPageViewModel.cs)the application works, where I have provided required file and called the function, which is NOT MVVM design. If you comment that line and uncomment line 79, it will not work. How can we solve this problem MVVM way?

以下是样本  代码

T o运行此应用程序,您必须在音乐目录中拥有至少一个MP3文件。 

To run this application you must have at lease one MP3 file in Music directory. 

<Page
    x:Class="MsMediaElement.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:MsMediaElement"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <Grid x:Name="MyGrid" Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <MediaElement x:Name="AppMediaElement" Source="{Binding RandomAccessStreamFile}" AutoPlay="True" />
    </Grid>
</Page>

using Windows.UI.Xaml.Controls;

// The Blank Page item template is documented at https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409

namespace MsMediaElement
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            DataContext = new MainPageViewModel(AppMediaElement);
        }
    }
}

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using Windows.Storage;
using Windows.Storage.Search;
using Windows.Storage.Streams;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;

namespace MsMediaElement
{
    public class MainPageViewModel : INotifyPropertyChanged
    {
        public ObservableCollection<string> MusicCollection { get; } = new ObservableCollection<string>();
        public event PropertyChangedEventHandler PropertyChanged;
        private readonly MediaElement _appMediaElement;

        protected void NotifyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public MainPageViewModel(MediaElement mediaPlayer)
        {
            LoadResourceFiles();
            _appMediaElement = mediaPlayer;
        }


        private IRandomAccessStreamWithContentType _randomAccessStreamFile;
        public IRandomAccessStreamWithContentType RandomAccessStreamFile
        {
            get => _randomAccessStreamFile;
            set
            {
                _randomAccessStreamFile = value;
                NotifyChanged("RandomAccessStreamFile");
            }
        }

        private async void OnDisplayMessage(string strMessage)
        {
            var dialog = new MessageDialog(strMessage) { Title = "Info ?" };
            dialog.Commands.Add(new UICommand { Label = "Ok", Id = 0 });
            //  dialog.Commands.Add(new UICommand { Label = "Cancel", Id = 1 });

            var res = await dialog.ShowAsync();
        }

        private async void LoadResourceFiles()
        {
            var musicQueryOptions = new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".mp3" })
            {
                FolderDepth = FolderDepth.Shallow
            };

            var musicQuery = KnownFolders.MusicLibrary.CreateFileQueryWithOptions(musicQueryOptions);

            IReadOnlyList<StorageFile> musicFilesList = await musicQuery.GetFilesAsync();
            if (musicFilesList.Count == 0)
            {
                OnDisplayMessage("There are no Music in your Music folder.");
                return;
            }
         
            foreach (var sf in musicFilesList)
            {
                MusicCollection.Add(sf.Name);
            }

            string str = MusicCollection[0];
            StorageFile file = await KnownFolders.MusicLibrary.GetFileAsync(str);
            
               IRandomAccessStreamWithContentType content = await file.OpenReadAsync();
             _appMediaElement.SetSource(content,content.ContentType);
           // RandomAccessStreamFile = content;

            //using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
            //{
            //    MediaStreamSample streamSample = await MediaStreamSample.CreateFromStreamAsync(fileStream, (uint)fileStream.Size, TimeSpan.Zero);
            //    _AppMediaElement.SetMediaStreamSource(streamSample);
            //}

        }
    }
}


谢谢



Agha Khan

Thanks


Agha Khan

推荐答案

嗨Agha,

MediaElement的Source属性类型是
Uri
,而不是IRandomAccessStreamWithContentType。因此,如果将它绑定到IRandomAccessStreamWithContentType属性,它将永远不会工作。

The Source property type of MediaElement is Uri, not IRandomAccessStreamWithContentType. So, if you bind it to a IRandomAccessStreamWithContentType property, it will never work.

在您的情况下,您最好定义一个MediaElement属性并将其绑定到ContentControl,如下面的代码示例所示:

In your case, you’d better define a MediaElement property and bind it to a ContentControl as the following code sample:

<ContentControl Content="{Binding Video}"></ContentControl>


private MediaElement _video;
        public MediaElement Video
        {
            get { return _video; }
            set
            {
                _video = value;
                NotifyChanged("Video");
            }
        }


private async void LoadResourceFiles()
        {
            ......
            
            var content = await file.OpenAsync(FileAccessMode.Read);
            Video.SetSource(content,file.FileType);

        }

最好的问候,

Xavier Eoro



Xavier Eoro


这篇关于[UWP] MediaElement和MVVM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆