I'm using the Xam.Plugin.Media to take a picture. In looking at the example code on git he does several checks to see if a camera is available etc. If there is an issue he uses the xamarin DisplayAlert. Being a good boy, I wired up a button to a command to "take the picture". So now I'm in my viewmodel checking for camera issues and need to display an alert. The question is, is it ok to use the eventaggregator to fire an event and subscribe to it in the view? I just want to tell the ui to throw an alert. All the things I've read re: the eventaggregator seem to suggest it's for communicating between view models. How would you handle this? Thanks ... Ed
0
votes
1 Answers
0
votes
From what you're describing you wouldn't want the Event Aggregator anywhere in the mix.
You can implement the following for a working app with Xam.Plugin.Media and Prism Forms
App.xaml.cs
public partial class App : PrismApplication
{
public App() : base()
{
}
protected override void OnInitialized()
{
InitializeComponent();
NavigationService.NavigateAsync("MainPage");
}
protected override void RegisterTypes()
{
Container.RegisterTypeForNavigation<MainPage>();
Container.RegisterInstance(CrossMedia.Current);
}
}
MainPage.xaml
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="AwesomePhotos.Views.MainPage">
<Grid Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="40" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Button Text="Snap Photo"
Command="{Binding TakePhotoCommand}"
HorizontalOptions="CenterAndExpand"
VerticalOptions="CenterAndExpand" />
<Image Source="{Binding Image}" Aspect="AspectFit" Grid.Row="1" />
</Grid>
</ContentPage>
MainPageViewModel.cs
public class MainPageViewModel : BindableBase
{
IMedia _media;
IPageDialogService _pageDialogService { get; }
public MainPageViewModel(IPageDialogService pageDialogService, IMedia media)
{
_media = media;
_pageDialogService = pageDialogService;
TakePhotoCommand = new DelegateCommand(OnTakePhotoCommandExecuted);
}
public DelegateCommand TakePhotoCommand { get; }
private ImageSource _image;
public ImageSource Image
{
get { return _image; }
set { SetProperty(ref _image, value); }
}
private async void OnTakePhotoCommandExecuted()
{
await _media.Initialize();
if (!_media.IsCameraAvailable || !_media.IsTakePhotoSupported)
{
await _pageDialogService.DisplayAlertAsync("No Camera", ":( No camera available.", "OK");
return;
}
var file = await _media.TakePhotoAsync(new StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg"
});
if (file == null)
return;
await _pageDialogService.DisplayAlertAsync("File Location", file.Path, "OK");
Image = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});
}
}