Namespaces

Variants
Actions

Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries over the next few weeks. Thanks for all your past and future contributions.

Como usar Cimbalino Windows Phone Toolkit Media Library – MediaLibraryService

From Wiki
Jump to: navigation, search

Este artigo mostra como usar o Cimbalino Windows Phone Toolkit Media Library - MediaLibraryService.


WP Metro Icon WP8.png
Article Metadata
Code Example
Source file: Exemplo MediaLibraryService(github)
Tested with
SDK: Windows Phone 8.0 SDK, Windows Phone 7.1.1. SDK
Devices(s): Nokia Lumia 800, Nokia Lumia 920, Nokia Lumia 925
Compatibility
Platform(s):
Windows Phone 8
Article
Translated:
By saramgsilva
Last edited: saramgsilva (10 Jan 2014)

Contents

Introdução

Cimbalino Windows Phone Toolkit é um conjunto de itens uteis e poderosos para ajudar na implementação de aplicações Windows Phone. Projeto base do toolkit contendo serviços para implementação do padrão de MVVM, conversores, classes auxiliares, métodos de extensões;

  • Cimbalino.Phone.Toolkit.MediaLibrary - Projeto do toolkit contendo serviços para implementação do padrão de MVVM com acesso à biblioteca de imagens, músicas e vídeos.

Note.pngNote: é preciso definir a capacidade ID_CAP_MEDIALIB_PHOTO no ficheiro manifest.

Contruindo o exemplo

O código fonte pode ser obtido em Exemplo MediaLibraryService(github).

Os pacotes estão disponíveis em Nuget Package Manager (para ambos os "targets") e podem ser instalados, para mais detalhes consultar: Como instalar os pacotes Cimbalino Windows Phone Toolkit. O exemplo deste artigo usa MVVM Light para ajudar na implementação do padrão MVVM, para mais detalhes consultar:

Registando os serviços

Devemos começar por registar cada serviço no ViewModelLocator, como podemos ver de seguida:

using Cimbalino.Phone.Toolkit.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Ioc;
using Microsoft.Practices.ServiceLocation;
 
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
 
if (!SimpleIoc.Default.IsRegistered<INavigationService>())
{
SimpleIoc.Default.Register<INavigationService, NavigationService>();
}
 
if (!SimpleIoc.Default.IsRegistered<IMediaLibraryService>())
{
SimpleIoc.Default.Register<IMediaLibraryService, MediaLibraryService>();
}
if (!SimpleIoc.Default.IsRegistered<ICameraCaptureService>())
{
SimpleIoc.Default.Register<ICameraCaptureService, CameraCaptureService>();
}
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<AlbunsViewModel>();
SimpleIoc.Default.Register<PicturesViewModel>();
}
 
/// <summary>
/// Gets the main view model.
/// </summary>
/// <value>
/// The main view model.
/// </value>
public MainViewModel MainViewModel
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
 
/// <summary>
/// Gets the albuns view model.
/// </summary>
/// <value>
/// The albuns view model.
/// </value>
public AlbunsViewModel AlbunsViewModel
{
get
{
return ServiceLocator.Current.GetInstance<AlbunsViewModel>();
}
}
 
/// <summary>
/// Gets the pictures view model.
/// </summary>
/// <value>
/// The pictures view model.
/// </value>
public PicturesViewModel PicturesViewModel
{
get
{
return ServiceLocator.Current.GetInstance<PicturesViewModel>();
}
}
 
/// <summary>
/// Cleanups.
/// </summary>
public static void Cleanup()
{
// TODO Clear the ViewModels
var viewModelLocator = (ViewModelLocator)App.Current.Resources["Locator"];
viewModelLocator.MainViewModel.Cleanup();
}
}

Implementando a ViewModel

Em seguinda devemos implementar o MainViewModel, como podemos ver de seguida:

using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
 
using Cimbalino.Phone.Toolkit.Services;
 
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight;
 
/// <summary>
/// This class contains properties that the main View can data bind to.
/// </summary>
public class MainViewModel : ViewModelBase
{
/// <summary>
/// The navigation service
/// </summary>
private readonly INavigationService _navigationService;
 
/// <summary>
/// The media library service
/// </summary>
private readonly IMediaLibraryService _mediaLibraryService;
 
/// <summary>
/// The camera capture service
/// </summary>
private readonly ICameraCaptureService _cameraCaptureService;
 
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
/// <param name="navigationService">The navigation service.</param>
/// <param name="mediaLibraryService">The media library service.</param>
/// <param name="cameraCaptureService">The camera capture service.</param>
public MainViewModel(INavigationService navigationService, IMediaLibraryService mediaLibraryService, ICameraCaptureService cameraCaptureService)
{
_navigationService = navigationService;
_mediaLibraryService = mediaLibraryService;
_cameraCaptureService = cameraCaptureService;
ShowAlbunsCommand =new RelayCommand(ShowAlbuns);
ShowPicturesCommand = new RelayCommand(ShowPictures);
SavePictureCommand = new RelayCommand(SavePicture);
}
 
/// <summary>
/// Saves the picture.
/// </summary>
private void SavePicture()
{
_cameraCaptureService.Show(CameraCapetureResult);
}
 
/// <summary>
/// Shows the pictures.
/// </summary>
private void ShowPictures()
{
_navigationService.NavigateTo(new Uri("/PicturesPage.xaml", UriKind.Relative));
}
 
/// <summary>
/// Shows the albuns.
/// </summary>
private void ShowAlbuns()
{
_navigationService.NavigateTo(new Uri("/AlbunsPage.xaml", UriKind.Relative));
}
 
/// <summary>
/// Gets the show albuns command.
/// </summary>
/// <value>
/// The show albuns.
/// </value>
public ICommand ShowAlbunsCommand { get; private set; }
/// <summary>
/// Gets the show pictures command.
/// </summary>
/// <value>
/// The show pictures command.
/// </value>
public ICommand ShowPicturesCommand { get; private set; }
 
/// <summary>
/// Gets the sava picture command.
/// </summary>
/// <value>
/// The sava picture command.
/// </value>
public ICommand SavePictureCommand { get; private set; }
 
/// <summary>
/// Cameras the capeture result.
/// </summary>
/// <param name="photoResult">The photo result.</param>
private async void CameraCapetureResult(Microsoft.Phone.Tasks.PhotoResult photoResult)
{
if (photoResult.ChosenPhoto != null)
{
_mediaLibraryService.SavePicture("CimbalinoPicture",photoResult.ChosenPhoto);
}
}
}

e podemos implementar PicturesViewModel como podemos ver de seguida:

using Cimbalino.Phone.Toolkit.Services;
 
using GalaSoft.MvvmLight;
 
using Microsoft.Xna.Framework.Media;
 
/// <summary>
/// This class contains properties that the main View can data bind to.
/// </summary>
public class PicturesViewModel:ViewModelBase
{
/// <summary>
/// The media library service
/// </summary>
private readonly IMediaLibraryService _mediaLibraryService;
 
/// <summary>
/// Initializes a new instance of the <see cref="PicturesViewModel" /> class.
/// </summary>
/// <param name="mediaLibraryService">The media library service.</param>
public PicturesViewModel(IMediaLibraryService mediaLibraryService)
{
_mediaLibraryService = mediaLibraryService;
}
 
/// <summary>
/// Gets the pictures.
/// </summary>
/// <value>
/// The pictures.
/// </value>
public PictureCollection Pictures
{
get
{
return _mediaLibraryService.Pictures;
}
}
}

e podemos implementar AlbunsViewModel como podemos ver de seguida:

 using Cimbalino.Phone.Toolkit.Services;
 
using Microsoft.Xna.Framework.Media;
 
public class AlbunsViewModel
{
/// <summary>
/// The media library service
/// </summary>
private readonly IMediaLibraryService _mediaLibraryService;
 
/// <summary>
/// Initializes a new instance of the <see cref="PicturesViewModel" /> class.
/// </summary>
/// <param name="mediaLibraryService">The media library service.</param>
public AlbunsViewModel(IMediaLibraryService mediaLibraryService)
{
_mediaLibraryService = mediaLibraryService;
}
 
/// <summary>
/// Gets a lbuns.
/// </summary>
/// <value>
/// Albuns.
/// </value>
public AlbumCollection Albuns
{
get
{
return _mediaLibraryService.Albums;
}
}
}

Implementando a View

A MainPage.xaml será algo do género:

<phone:PhoneApplicationPage x:Class="CimbalinoSample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
DataContext="{Binding MainViewModel,
Source={StaticResource Locator}}"

FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
Orientation="Portrait"
SupportedOrientations="Portrait"
shell:SystemTray.IsVisible="True"
mc:Ignorable="d">
 
<!-- LayoutRoot is the root grid where all page content is placed -->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
 
<!-- TitlePanel contains the name of the application and page title -->
<StackPanel x:Name="TitlePanel"
Grid.Row="0"
Margin="12,17,0,28">
<TextBlock Margin="12,0"
Style="{StaticResource PhoneTextTitle2Style}"
Text="Cimbalino Sample" />
<TextBlock Margin="9,-7,0,0"
Style="{StaticResource PhoneTextTitle2Style}"
Text="MediaLibraryService" />
</StackPanel>
 
<!-- ContentPanel - place additional content here -->
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<TextBlock TextWrapping="Wrap">This samples has the goal to show how to use Cimbalino Windows Phone Toolkit Media Library - MediaLibraryService</TextBlock>
 
<Button Margin="0,209,0,303"
Command="{Binding SavePictureCommand}"
Content="Save Picture" />
<Button Margin="2.985,332.896,-2.985,179.104"
Command="{Binding ShowPicturesCommand}"
Content="Show Pictures" RenderTransformOrigin="0.5,0.5" UseLayoutRounding="False" d:LayoutRounding="Auto" >
<Button.RenderTransform>
<CompositeTransform SkewX="1.914" TranslateX="-2.205"/>
</Button.RenderTransform>
</Button>
 
<Button Margin="0,447,0,65"
Command="{Binding ShowAlbunsCommand}"
Content="Show Albuns" />
</Grid>
</Grid>
</phone:PhoneApplicationPage>


A PicturesPage.xaml será algo do género:

<phone:PhoneApplicationPage x:Class="CimbalinoSample.PicturesPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Extras.WP8"
xmlns:converters="clr-namespace:CimbalinoSample.Converters"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
DataContext="{Binding PicturesViewModel,
Source={StaticResource Locator}}"

FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
Orientation="Portrait"
SupportedOrientations="Portrait"
shell:SystemTray.IsVisible="True"
mc:Ignorable="d">
<phone:PhoneApplicationPage.Resources>
<converters:MedialibraryConverter x:Key="medialibraryConverter" />
</phone:PhoneApplicationPage.Resources>
<!-- LayoutRoot is the root grid where all page content is placed -->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
 
<!-- TitlePanel contains the name of the application and page title -->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Margin="12,0"
Style="{StaticResource PhoneTextTitle2Style}"
Text="Cimbalino Sample" />
<TextBlock Margin="9,-7,0,0"
Style="{StaticResource PhoneTextTitle2Style}"
Text="Pictures" />
</StackPanel>
 
<!-- ContentPanel - place additional content here -->
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0">
<ListBox ItemsSource="{Binding Pictures}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Height="100"
Source="{Binding Converter={StaticResource medialibraryConverter}}"
Stretch="Uniform" />
<TextBlock>
Name:<Run Text="{Binding Name}" />
</TextBlock>
<TextBlock>
Width:<Run Text="{Binding Width}" />
</TextBlock>
<TextBlock>
Height:<Run Text="{Binding Height}" />
</TextBlock>
<TextBlock>
Date:<Run Text="{Binding Date}" />
</TextBlock>
<TextBlock>
Album:<Run Text="{Binding Album}" />
<LineBreak />
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
 
</phone:PhoneApplicationPage>

Cujo MediaLibraryConverter é

/// <summary>
/// The media library converter class
/// </summary>
public class MedialibraryConverter : IValueConverter
{
/// <summary>
/// Converts the specified value.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="targetType">Type of the target.</param>
/// <param name="parameter">The parameter.</param>
/// <param name="culture">The culture.</param>
/// <returns></returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
var image = (Microsoft.Xna.Framework.Media.Picture) value;
return PictureDecoder.DecodeJpeg(image.GetImage());
}
 
/// <summary>
/// Converts the back.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="targetType">Type of the target.</param>
/// <param name="parameter">The parameter.</param>
/// <param name="culture">The culture.</param>
/// <returns></returns>
/// <exception cref="System.NotImplementedException"></exception>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}


A AlbunsPage.xaml será algo do género:

<phone:PhoneApplicationPage x:Class="CimbalinoSample.AlbunsPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
Orientation="Portrait"
DataContext="{Binding AlbunsViewModel,
Source={StaticResource Locator}}"

SupportedOrientations="Portrait"
shell:SystemTray.IsVisible="True"
mc:Ignorable="d">
 
<!-- LayoutRoot is the root grid where all page content is placed -->
<Grid x:Name="LayoutRoot" Background="Transparent">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
 
<!-- TitlePanel contains the name of the application and page title -->
<StackPanel Grid.Row="0" Margin="12,17,0,28">
<TextBlock Margin="12,0"
Style="{StaticResource PhoneTextTitle2Style}"
Text="Cimbalino Sample" />
<TextBlock Margin="9,-7,0,0"
Style="{StaticResource PhoneTextTitle2Style}"
Text="Albuns" />
</StackPanel>
 
<!-- ContentPanel - place additional content here -->
<Grid x:Name="ContentPanel"
Grid.Row="1"
Margin="12,0,12,0" >
<ListBox ItemsSource="{Binding Albuns}">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock>
Name :<Run Text="{Binding Name}" />
</TextBlock>
<TextBlock>
Artist: <Run Text="{Binding Artist}" />
</TextBlock>
<TextBlock>
Duration :<Run Text="{Binding Duration}" />
</TextBlock>
<TextBlock>
Genre :<Run Text="{Binding Genre}" />
</TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</Grid>
 
</phone:PhoneApplicationPage>
This page was last modified on 10 January 2014, at 10:31.
156 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×