Search code examples
silverlightitemscontrolsilverlight-5.0mediaelementstackpanel

How do I add a dynamic list of MediaElements to a StackPanel in Silverlight 5?


I am working in C# and Silverlight 5, and I am trying to display one or more audio and/or video files that have been retrieved from a database table as a byte array. I decided the best way to get those byte arrays into a usable format was to create an ObservableCollection list in my ViewModel that gets populated during the service call:

mediaFiles = new ObservableCollection<MediaElement>();
foreach (FileUpload fu in FileUploadMediaTable)
{
   using (MemoryStream ms = new MemoryStream(fu.bytes, 0, fu.bytes.Length))
   {
      MediaElement me = new MediaElement();
      me.SetSource(ms);
      mediaFiles.Add(me);
   }
}

Now, my only problem is figuring out how to add these media elements into the view. I was thinking of creating a new ItemsControl with a custom DataTemplate that defines the buttons for playback that embeds the MediaElements in a StackPanel, but how would I associate each of the buttons with that specific MediaElement?

EDIT: Of course, I guess I could just create a list of byte arrays and add a MediaElement object to the DataTemplate and pass the byte array in the source with a Bytes2ImageConverter defined. Of course, maybe I could skip that step and just bind the MediaElement's source to a MemoryStream object created on each byte array. I am not sure of the best way to proceed (or if this stuff is even possible).


Solution

  • You can create a Model class, which will contain Media source (will be bound to the MediaElement Source property) and addition data, which needed (caption, author, etc). You can use a list box for displaying all these videos. You should create an item template and use it for listbox items. This item template will contain a media element and a play/stop button, where you will bind a command. Command will be placed in your ViewModel class and you can bind a Model as command parameter. So, you can get access to medial source (Model class), which should be played. What about playing/stopping video: you can create a media element helper, which will contain an attached dependency property (for example: IsPlaying, in your model class). You will bind a true/false value for playing/stopping the video. Thats all.