Accessing WebView2 Control And It's properties In A C# Class Library
Team,
Output
In a situation wherein you need to access a WebView2 control properties in a class library and that the WebView2 control is added in a WPF project, all you need to do is to reference the Microsoft.Web.WebView2.Wpf.dll and Microsoft.Web.WebView2.Core.dll from the WPF project into the class library.
The sample code below is a utility class located in a class library project which has a WebView2 control object that performs navigation to a url that is set from the WPF project.
public static class WebBrowserUtility { public static readonly DependencyProperty BindableSourceProperty = DependencyProperty.RegisterAttached("BindableSource", typeof(string), typeof(WebBrowserUtility), new UIPropertyMetadata(null, BindableSourcePropertyChanged)); public static string GetBindableSource(DependencyObject obj) { return (string)obj.GetValue(BindableSourceProperty); } public static void SetBindableSource(DependencyObject obj, string value) { obj.SetValue(BindableSourceProperty, value); } public async static void BindableSourcePropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e) { if (o.GetType() == typeof(WebBrowser)) { var webBrowser = (WebBrowser)o; webBrowser.NavigateToString((string)e.NewValue); } else { var webBrowser = (WebView2)o; await webBrowser.EnsureCoreWebView2Async(); webBrowser.NavigateToString((string)e.NewValue); } } }
Comments
Post a Comment