How to track changes to Content WebView2 - c#

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

You have two options
Set the Mode to TwoWay, and remove the UpdateSourceTrigger=Explicit
Source="{Binding MyHtml, Mode=TwoWay}"
If you want to keep Explicit mode, you have to call UpdateSource() to update the bound property (i.e.MyHtml). This can be done by handling NavigationCompleted 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.

Related

My UserControl's TextBlock binding doesn't update even once

I know this has been asked for many times. I read a lot of them and tried different ways but still could not get it to work.
The xaml code is a UserControl:
<Grid Name="middle">
<d:TextBlock Text="{x:Bind LayerNodeData.CleanName, Mode=OneWay, UpdateSourceTrigger=PropertyChanged}" Foreground="WhiteSmoke" FontSize="12" FontFamily="Arial" VerticalAlignment="Center" RelativePanel.RightOf="visibleUI" DoubleTapped="OnEditNameBegin" />
</Grid>
I set both this.DataContext and the Grid's DataContext to the data instance.
c#
public ucLayerRow(ImageLayerNode data)
{
LayerNodeData = data;
DataContext = LayerNodeData;
this.InitializeComponent();
middle.DataContext = LayerNodeData;
LayerNodeData.NotifyPropertyChanged("CleanName"); // test if it work
RefreshUI();
}
Model class
public partial class ImageLayerNode : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
// PropertyChanged is always null.
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
public string mCleanName = string.Empty;
public string CleanName {
get => mCleanName;
set { mCleanName = value; NotifyPropertyChanged();}
}
....
}
I tried add a breakpoint to the PropertyChanged and found that it is always null and thus never get called. I also tried changing the mode to OneWay, TwoWays but still nothing.
The textblock is away empty not even getting a value once.
The user control is added like this to the main page. Not sure if it is related.
var rowUI = new ucLayerRow(layerNode);
layerContainer.Children.Add(rowUI);
My UserControl's TextBlock binding doesn't update even once
During the testing, the problem looks that you use design time for usercontrol. <d:TextBlock/> please remove d: and make your usercontrol like the following.
Xaml
<Grid>
<TextBlock
VerticalAlignment="Center"
FontFamily="Arial"
FontSize="12"
Foreground="Red"
Text="{x:Bind LayerNodeData.CleanName, Mode=OneWay}" />
</Grid>
Code behind
public sealed partial class ucLayerRow : UserControl
{
public ucLayerRow(ImageLayerNode data)
{
this.InitializeComponent();
LayerNodeData = data;
}
public ImageLayerNode LayerNodeData { get; set; }
}
public partial class ImageLayerNode : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
// PropertyChanged is always null.
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
private string mCleanName = string.Empty;
public string CleanName
{
get => mCleanName;
set { mCleanName = value; NotifyPropertyChanged(); }
}
}

PropertyChanged Event handler is always null also with OneWay specification

i created a simple ListView in XAML which should bind to an ObservablaCollection:
<PivotItem x:Uid="pvItemMusic" Header="Music">
<StackPanel>
<TextBlock Name="tbSelectMusicHeader" Text="Select directories that should be included into your library" FontSize="18" Margin="20"></TextBlock>
<Button Name="btnSelectSourcePath" Content="Add path" Margin="30,10,0,10" Click="btnSelectSourcePath_Click"></Button>
<ListView Name="lvPathConfiguration" DataContext="{StaticResource configurationVM}" ItemsSource="{Binding MusicBasePathList, Mode=OneWay}">
<ListView.ItemTemplate>
<DataTemplate>
<RelativePanel>
<TextBlock Name="tbPath" Text="{Binding Mode=OneWay}" RelativePanel.AlignTopWithPanel="True" VerticalAlignment="Center" Width="400" Margin="20"></TextBlock>
<Button Name="btnRemovePath" x:Uid="btnRemovePath" Content="Remove" RelativePanel.RightOf="tbPath" Margin="10" Height="48"></Button>
</RelativePanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</PivotItem>
The namespace of my ViewModel is imported by
xmlns:applicationVM="using:Crankdesk.CrankHouseControl.ViewModel.Application"
and the Page Resource i added my ViewModel:
<Page.Resources>
<applicationVM:ConfigurationViewModel x:Key="configurationVM"></applicationVM:ConfigurationViewModel>
</Page.Resources>
btnSelectSourcePath should add a path to the list of source pathes that are stored in ViewModel, which will be done in CodeBehind:
private async void btnSelectSourcePath_Click(object sender, RoutedEventArgs e)
{
FolderPicker picker = new Windows.Storage.Pickers.FolderPicker();
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.MusicLibrary;
picker.FileTypeFilter.Add("*");
StorageFolder folder = await picker.PickSingleFolderAsync();
if (folder != null)
{
// Save path to configuration
App.ConfigurationViewModel.MusicBasePathList.Add(folder.Path);
}
}
In ViewModel the "INotifyPropertyChanged" Event is used and i use the "CollectionChanged" Event of my ObersableCollection to fire the PropertyChanged Event. When i add a path in debug mode, the RaisePropertyChanged Method will be executed, but the "handler" property is always NULL.
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Here is my whole ViewModel:
namespace Crankdesk.CrankHouseControl.ViewModel.Application
{
public class ConfigurationViewModel : INotifyPropertyChanged
{
private ObservableCollection<string> _musicBasePathList;
public ObservableCollection<string> MusicBasePathList
{
get
{
return _musicBasePathList;
}
set
{
_musicBasePathList = value;
}
}
public event PropertyChangedEventHandler PropertyChanged;
public ConfigurationViewModel()
{
_musicBasePathList = new ObservableCollection<string>();
_musicBasePathList.CollectionChanged += _musicBasePathList_CollectionChanged;
}
private void _musicBasePathList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
RaisePropertyChanged(nameof(MusicBasePathList));
}
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
What do i wrong here? I know i ask this question the 34th time here, but i didn't find a solution. In most cases they forgot to specify OneWay or TwoWay, but that's not the case here.
Thanks in advance....
Dave
You have at minimum two instances of ConfigurationViewModel in your application.
App.ConfigurationViewModel
defined in the page ressources as configurationVM
The view is bound to the 2. instance and in code behind you modify the 1. instance.

Bind label Content to string property

I want to bind the content of a label to a local property called "Status".
Codesnipped:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var logFilePath = GetPathToAppDirPlusLocalPath("LogFiles/MainLog.txt");
MainLog = new Log(#logFilePath);
MainLog.Add("MainWindow initialized");
this.DataContext = this;
}
private string _Status = null;
public string Status
{
get
{
return _Status;
}
set
{
_Status = value;
NotifyPropertyChanged("Status"); //Call the method to set off the PropertyChanged event.
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void NotifyPropertyChanged(string propertyName = "")
{
var handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
XAML:
<Border x:Name="brd_Status" Grid.Row="9" Grid.ColumnSpan="10"
HorizontalAlignment="Stretch" VerticalAlignment="Bottom"
Background="Black" DataContext="Status">
<Label x:Name="lbl_Status" Content="{Binding Path=Status,UpdateSourceTrigger=PropertyChanged}"
Grid.Row="9" Grid.ColumnSpan="10"
HorizontalAlignment="Center" VerticalAlignment="Bottom"
FontSize="16" Foreground="White" FontFamily="Asenine">
</Label>
</Border>
I also tried Content = {Binding Status...} but makes no difference.
The label is just "null", while the property "Status" is "abcd1234...".
I debugged it and but, I am not sure where to search for a failure...
The issue is that MainWindow is not implementing INotifyPropertyChanged so even though you have and are raising the appropriate event, the runtime hasn't registered for it.
Change your class definition to:
public partial class MainWindow : Window, INotifyPropertyChanged
Also consider using a proper view model (look up MVVM), puting INPC on a view object is very bad design, and note that an UpdateSourceTrigger on a Label is useless as Label controls cannot be changed in the UI.

What am I doing wrong in this binding of a dependency property in the code behind (of a view) to a property its viewmodel?

A couple of other posts seem to indicate that data can be shared between a View's code behind and viewmodel by binding the dependency property in the code behind and property in the viemodel. Also, I have read that the DP should be in the code behind when itself is being bound in a Main Window/User Control relationship.
The following is from the code behind (SetupUC)
public static readonly DependencyProperty UC1Property =
DependencyProperty.Register(
"UC1", typeof(string), typeof(SetupUC),
new FrameworkPropertyMetadata()
{
PropertyChangedCallback = OnUC1Changed,
BindsTwoWayByDefault = true
});
public string UC1
{
get { return (string)GetValue(UC1Property); }
set
{
SetValue(UC1Property, value);
}
}
public SetupUC()
{
InitializeComponent();
SetupViewModel svm = new SetupViewModel();
this.DataContext = svm;
Binding binding = new Binding("ViewModelStringProperty") { Source = svm, Mode = BindingMode.TwoWay };
BindingOperations.SetBinding(this, SetupUC.UC1Property, binding);
}
and the viewmodel (SetupViewModel)
private string _viewModelStringProperty;
public string ViewModelStringProperty
{
get { return _viewModelStringProperty; }
set
{
_viewModelStringProperty = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("ViewModelStringProperty"));
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
In debugging, UC1 seems to always be updated correctly from the Main Window as its changes are reflected in the user control view. However, in the viewmodel, ViewModelStringProperty does not ever seem to be updated - it's always null. Full disclosure(!), the following is how UC1 is bound in the user control XAML
<TextBox x:Name="tbx1" HorizontalAlignment="Left" Height="23" Margin="159,22,0,0" TextWrapping="Wrap" Text="{Binding UC1, ElementName=root}" VerticalAlignment="Top" Width="120" RenderTransformOrigin="0.017,0.304"/>
Again, this part seems to be fine, it's getting data to ViewModelStringProperty in the viewmodel that is not.
To ensure your changes in your TextBox are immediately pushed to the DependencyProperty and subsequently the view-model, ensure you have UpdateSourceTrigger=PropertyChanged on your TextBox.Text binding, i.e.:
Text="{Binding UC1, ElementName=root, UpdateSourceTrigger=PropertyChanged}"
With this, my example worked perfectly fine.
If this doesn't help, I suggest adding two additional TextBlocks, one bound to the UC1 and one bound to ViewModelStringProperty, this will make it easier to tell which are getting updated correctly, e.g.:
<StackPanel>
<TextBox Text="{Binding UC1, ElementName=Root, UpdateSourceTrigger=PropertyChanged}" />
<TextBlock Text="{Binding UC1, ElementName=Root}" />
<TextBlock Text="{Binding ViewModelStringProperty}" />
</StackPanel>

Binding textblock text to property on load

I'm trying to display the number of records retrieved by the query after the window loads. Here's what I have in my XAML:
<TextBlock Name="numRecordsAnalyzed_TAtab" TextWrapping="Wrap" Margin="12,0,0,4" Grid.RowSpan="2">
<Run Text="Records Found: " Foreground="{StaticResource Foreground}" FontSize="12"/>
<Run Text="{Binding Numrecords}" Foreground="Red" FontSize="12"/>
</TextBlock>
Here's my c#:
private int numOfrecords = 0;
public event PropertyChangedEventHandler PropertyChanged;
public string Numrecords
{
get { return Convert.ToString(numOfrecords); }
set
{
OnPropertyChanged("NumOfrecords");
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
Then I add this to get the number of records and when I debug I see that the variable holds the number and everything but nothing is displayed in the window when the window launches:
numOfrecords = OpenTradesQuery.Count();
What am I missing?
You need to raise PropertyChanged event to notify GUI to update.
Declare property of type int, WPF will automaically call ToString() on your property, you need not to worry about that.
public int Numrecords
{
get { return numOfrecords; }
set
{
if(numOfrecords != value)
{
numOfrecords = value;
OnPropertyChanged("Numrecords");
}
}
}
Set the property:
Numrecords = penTradesQuery.Count();
You can set DataContext in code behind after InitializeComponent() in constructor of Window/UserControl:
DataContext = this;
Also, you can set it in XAML at root level like this:
<Window DataContext="{Binding RelativeSource={RelativeSource Self}}"/>

Categories

Resources