我试图在Windows 8.1通用应用程序中启动和停止相机的MediaCapture预览。在的OnNavigatedTo方法中,我有以下代码:调用MediaCapture.StartPreviewAsync时发生“InvalidOperationException:方法在意外的时间被调用”
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
var scanItemsParameter = e.Parameter as ScanItemParameter;
if (scanItemsParameter != null)
{
((ScanItemViewModel)DataContext).ScanCallback = scanItemsParameter.ScanCallback;
}
try
{
HardwareButtons.CameraPressed += HardwareButtonsOnCameraPressed;
HardwareButtons.CameraHalfPressed += HardwareButtonsOnCameraHalfPressed;
DisplayInformation.GetForCurrentView().OrientationChanged += OnOrientationChanged;
if (!_mediaInitialized)
{
var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
if (cameras.Count < 1)
{
return;
}
MediaCaptureInitializationSettings settings;
settings = new MediaCaptureInitializationSettings
{
VideoDeviceId = cameras[0].Id,
PhotoCaptureSource = PhotoCaptureSource.Photo
};
await _mediaCapture.InitializeAsync(settings);
VideoCapture.Source = _mediaCapture;
_mediaInitialized = true;
}
SetOrientation(DisplayInformation.GetForCurrentView().CurrentOrientation);
await _mediaCapture.StartPreviewAsync();
await _mediaCapture.VideoDeviceController.ExposureControl.SetAutoAsync(true);
if (_mediaCapture.VideoDeviceController.FocusControl.FocusChangedSupported)
{
var focusSettings = new FocusSettings();
focusSettings.AutoFocusRange = AutoFocusRange.Normal;
focusSettings.Mode = FocusMode.Auto;
focusSettings.WaitForFocus = true;
focusSettings.DisableDriverFallback = false;
_mediaCapture.VideoDeviceController.FocusControl.Configure(focusSettings);
}
_mediaCapture.VideoDeviceController.FlashControl.Auto = true;
}
catch (Exception ex)
{
var ex2 = ex;
throw;
}
}
在OnNavigatingFrom方法,我清理了一些事件处理程序,并调用MediaCapture.StopPreviewAsync()
:
protected override async void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
await _mediaCapture.StopPreviewAsync();
HardwareButtons.CameraPressed -= HardwareButtonsOnCameraPressed;
HardwareButtons.CameraHalfPressed -= HardwareButtonsOnCameraHalfPressed;
DisplayInformation.GetForCurrentView().OrientationChanged -= OnOrientationChanged;
}
呼叫正常工作,我第一次开该页面,但如果我离开页面并返回,我会得到一个InvalidOperationException。我错过了什么?
作为一个说明,我使用的MVVM光,如果说有什么区别...
在此先感谢您的帮助......
你怎么离开?我怀疑的问题是,这些事件并不是每次你离开应用程序时都被调用。例如,如果您使用的是暂停管理器,则当您暂停应用时(命中开始按钮,更改应用等),将调用NavigateFrom事件(这在调试时也不会发生),但是当您返回时不会调用NavigatedTo到应用程序。 – Romasz 2015-03-03 05:58:35
@Romasz我使用'NavigationService.NavigateTo()'和'NavigationService.GoBack()'方法来改变页面。当我使用后者时,'OnNavigatingFrom'方法中的代码被成功调用。至少在我第二次访问该页面时,“OnNavigatedTo”代码肯定会被调用。它一直在'StartPreviewAsync'方法中断。我认为它在应用程序暂停或主页按钮被按下时执行相同的操作。我还没有开始研究这些问题。 – 2015-03-03 13:18:33
您是否设置了您的页面的“NavigationCacheMode = NavigationCacheMode.Required;” - 如果您的MediaCapture不是导航可能返回* null *,那么您是否有可能这样做。我已经测试过样本,并应该工作,如果你有进一步的问题给我一个迹象。还使用OnNavigatedTo和From(仅)不是一个好主意,你应该慢慢开始研究这些问题;) – Romasz 2015-03-03 17:00:35