Donate

Accessing WebView2 Control And It's properties In A C# Class Library

Team,

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.
Accessing WebView2 Control And It's properties In A C# 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);
        }            
    }
}
Output
Accessing WebView2 Control And It's properties In A C# Class Library

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

Bootstrap Modal In ASP.NET MVC With CRUD Operations