How to subscribe to Navigated event from the WebBrowser control on a ViewModel? (MVVM)

35 Views Asked by At

So basically I'm trying to subscribe to the Navigated event on the WebBrowser control so I can get the source of the WebBrowser, but I have no idea how to subscribe to it from the ViewModel

I have tried subscribing to it from code-behind and then sending a message to the ViewModel (I'm using MVVM Light) but the ViewModel doesn't receive the message (an example of how I'm doing it)

(Code-behind)

// I don't remember the NavigatedArgs so I just put NavigatedArgs heh
WebBrowser_Navigated(object sender, NavigatedArgs)
{
      // Some logic
      var msg = new SendMessage() { property = param };                   
      Messenger.Default.Send(msg)
}

(ViewModel)

Messenger.Default.Register<SendMessage>
(
   this,
   (action) => ReceiveMessage(action)
);
1

There are 1 best solutions below

0
MrCoolAndroid On BEST ANSWER

So looking around I was able to do it by binding the event to a command on the XAML file with Interaction Triggers and then using the control as a CommandParameter:

        <WebBrowser x:Name="Browser" Grid.Row="1" Source="http://link.to.source">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Navigated">
                    <i:InvokeCommandAction Command="{Binding NavigatedCommand}" CommandParameter="{Binding RelativeSource=
                                   {RelativeSource
                                    Mode=FindAncestor,
                                    AncestorType={x:Type WebBrowser}}}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </WebBrowser>

and then handle it on the ViewModel:

        public RelayCommand<WebBrowser> NavigatedCommand { get; set; }

        public ViewModel()
        {
            NavigatedCommand = new RelayCommand<WebBrowser>((e) => DoStuff(e));
        }