It is necessary to track the link change in WebView 2. I have the following code in the VM:
VM
private Uri _myHtml;
public Uri MyHtml
{
get { return _myHtml; }
set
{
_myHtml = value;
CheckUri(MyHtml);
OnPropertyChanged();
OnPropertyChanged(nameof(MyHtml));
}
}
VMBASE
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
VIEW XAML
<Wpf:WebView2 Name="webView"
Source="{Binding MyHtml, UpdateSourceTrigger=Explicit}" Grid.RowSpan="2" Grid.ColumnSpan="3" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" />
Alas, the breakpoint on "set" is triggered only when the "MyHTML" variable is directly assigned a value. But when you change the URL in WebView2, nothing changes
CodePudding user response:
You have two options
- Set the
Mode
to TwoWay, and remove theUpdateSourceTrigger=Explicit
Source="{Binding MyHtml, Mode=TwoWay}"
- If you want to keep
Explicit
mode, you have to callUpdateSource()
to update the bound property (i.e.MyHtml
). This can be done by handlingNavigationCompleted
event like so..
In .xaml
<Wpf:WebView2
Source="{Binding MyHtml, UpdateSourceTrigger=Explicit, Mode=TwoWay}"
NavigationCompleted="WebView_OnNavigationCompleted" ..
In .xaml.cs
private void WebView_OnNavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs args)
{
if (args.IsSuccess)
{
var bindingExpression =
webView.GetBindingExpression(WebView2.SourceProperty);
bindingExpression?.UpdateSource();
}
}
Note that in both options you need Mode=TwoWay
.