2

I have a wpf user control that is hosted by a third party application as a non-modal dockable window. I would like to trigger an event with the window gets focus or when the mouse enters the window. This is a MVVM design. How do I bind the event handler of the Grid (not datagrid) or the UserControl to a method on the viewmodel. I want to avoid the xaml.cs code since I have to cast the datacontext into the expected viewmodel to make the call.

<UserControl x:Class="MVVMWithCommand.ChartExtentView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:local="clr-namespace:MVVMWithCommand"
         mc:Ignorable="d" 
         d:DesignHeight="300" d:DesignWidth="300" GotFocus="UserControl_GotFocus">
<UserControl.DataContext>
    <local:MyViewModel/>
</UserControl.DataContext>
<Grid GotFocus="Grid_GotFocus">

There were two problems combined. The solution in the link didn't work because of another problem.

This only partially anwsered the question WPF Binding UI events to commands in ViewModel combined with this it did: Could not load file or assembly 'System.Windows.Interactivity'

Alex Gray
  • 21
  • 5
  • 1
    Possible duplicate of [WPF Binding UI events to commands in ViewModel](https://stackoverflow.com/questions/4897775/wpf-binding-ui-events-to-commands-in-viewmodel) – Nick Aug 07 '18 at 20:05
  • The solution in that question doesn't work in this case – Alex Gray Aug 08 '18 at 15:54
  • Using Nick Suggestion in this link https://stackoverflow.com/questions/4897775/wpf-binding-ui-events-to-commands-in-viewmodel (with the addition of setting an x:Name property on the i:InvokeCommandAction as per here https://stackoverflow.com/questions/13514027/could-not-load-file-or-assembly-system-windows-interactivity) makes the command trigger when the controls inside the grid get focus but not when the user control itself gets focus. Same with mouse enter. – Alex Gray Aug 08 '18 at 18:01
  • It absolutely does work. If you're not getting the result that you want then you need to clarify your question and better phrase what you're looking for. This certainly does bind the control's GotFocus event to a command in the ViewModel. – Nick Aug 08 '18 at 20:31
  • You are right Nick it works if you name the thing, it just wasn't what I expected. I am looking for a different solution now. – Alex Gray Aug 09 '18 at 18:57
  • What do you mean "if you name the thing"? Nothing in there requires you to do any additional naming. – Nick Aug 14 '18 at 15:27

0 Answers0