在视图中订阅Prism Eventaggregator?

时间:2017-04-28 10:04:29

标签: xamarin prism eventaggregator

我正在使用Xam.Plugin.Media来拍照。在git上查看示例代码时,他会进行几次检查以查看相机是否可用等。如果出现问题,他会使用xamarin DisplayAlert。作为一个好孩子,我按了一个按钮来命令“拍照”。所以现在我在我的viewmodel中检查相机问题并需要显示警告。问题是,使用eventaggregator来触发事件并在视图中订阅它是否可以?我只想告诉ui发出警报。我读过的所有内容都是:eventaggregator似乎建议在视图模型之间进行通信。你会怎么处理这个? 谢谢...... Ed

1 个答案:

答案 0 :(得分:0)

根据您的描述,您不希望事件聚合器在任何地方混合使用。

您可以对包含Xam.Plugin.MediaPrism 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;
        });
    }
}
相关问题