How to put webview in a WPF project using Swift

I am using Windows 10 to learn Swift. I THINK I created a new project in WPF. When I put a WebView into the Window1.xaml. It prompt error when I run it. It just modified from a simple hello world program. Thank you.

Window1.xaml

<?xml version=“1.0” encoding=“utf-8”?>
<Window x:Class=“WPFApplication.Window1”
xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation
xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml
Title=“using Swift” Height=“600” Width=“800”
>
<Grid>
<WebView Name=“webview1” Source=“https://www.google.com” />
</Grid>
</Window>

Error

E: Unknown type “{http://schemas.microsoft.com/winfx/2006/xaml/presentation}WebView” [C:\test\swift\silver\WPFApplication\WPFApplication\Window1.xaml (8)]

Antony,

I don’t believe WebView is a standard control provided by WPF? Some googling found me this article: https://docs.microsoft.com/en-us/windows/communitytoolkit/controls/wpf-winforms/webview,it seems you will need to add the Microsoft.Toolkit.Wpf.UI.Controls.WebView NuGet package reference to use this control, and follow the steps outlined in the article.

That said, I’m not familiar with he control, so I cannot comment further. But in general, any WPF-compliant third party controls will work with Swift just as they would with VC#.

hth,
marc

Marc,

Thank you for your reply. Since I don’t want to install Visual Studio, I use the original method.

Antony

1 Like

This should workmen Water, too; you can add the package reference via “Add References” and selecting the “NuGet Packages” tab. You will want something in the XAML like:

<?xml version="1.0" encoding="utf-8"?>
<Window x:Class="WPFApplication3.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:web="clr-namespace:Microsoft.Toolkit.Wpf.UI.Controls"
    Title="Window1" Height="300" Width="300"
    >
    <Grid>
        <web:WebView />
    </Grid>
</Window>

Note that it seems the Microsoft.Toolkit.Wpf.UI.Controls.WebView package only support .NET 4.6.2 or later, so you’ll need to increase the Target Framework setting of the default project (with is 4.5). Or use .NET Core.

Sample: WebView.zip (50.1 KB)

mh,

Thank you for your reply. I have not nuget tab in my Silver - Water. I think I don’t have .Net 4.6.2 when checking with wmic command. I got do not exist error when run your program.

What version of Water are you using, and are you sure your active project is a .NET project? The NuGet Packages tab has been there for a while…

What’s the exact error you get with the project i sent?

Thank you for your reply. I was tire yesterday, so hadn’t turn on my computer. Surprisingly, it works today. The Nuget tab appear and not dim.
Thank you

1 Like

Glad to hear!