Files
Learn-WinUI-3-Second-Edition/Chapter10/TemplateStudioSampleApp/Services/WebViewService.cs
T
2023-08-13 13:40:04 -04:00

51 lines
1.4 KiB
C#

using System.Diagnostics.CodeAnalysis;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Web.WebView2.Core;
using TemplateStudioSampleApp.Contracts.Services;
namespace TemplateStudioSampleApp.Services;
public class WebViewService : IWebViewService
{
private WebView2? _webView;
public Uri? Source => _webView?.Source;
[MemberNotNullWhen(true, nameof(_webView))]
public bool CanGoBack => _webView != null && _webView.CanGoBack;
[MemberNotNullWhen(true, nameof(_webView))]
public bool CanGoForward => _webView != null && _webView.CanGoForward;
public event EventHandler<CoreWebView2WebErrorStatus>? NavigationCompleted;
public WebViewService()
{
}
[MemberNotNull(nameof(_webView))]
public void Initialize(WebView2 webView)
{
_webView = webView;
_webView.NavigationCompleted += OnWebViewNavigationCompleted;
}
public void GoBack() => _webView?.GoBack();
public void GoForward() => _webView?.GoForward();
public void Reload() => _webView?.Reload();
public void UnregisterEvents()
{
if (_webView != null)
{
_webView.NavigationCompleted -= OnWebViewNavigationCompleted;
}
}
private void OnWebViewNavigationCompleted(WebView2 sender, CoreWebView2NavigationCompletedEventArgs args) => NavigationCompleted?.Invoke(this, args.WebErrorStatus);
}