title: Unable to dynamically set focus in WPF MVVM application
body: <p>I'm working on a WPF application using the MVVM pattern, and I have hit a problem with focus.</p>
  <p>I have full screen slide on 'overlays' and within each overlay I have a ContentPresenter that I use to display arbitrary view models/views by data binding it's content to a view model property I set in my data context, like so:</p>
  <pre><code>&lt;Grid Name=&quot;OverlayContainer&quot;
        FocusManager.IsFocusScope=&quot;True&quot;
        KeyboardNavigation.TabNavigation=&quot;Cycle&quot;
        IsEnabled=&quot;False&quot;&gt;
  
    &lt;Grid.RenderTransform&gt;
      &lt;TranslateTransform x:Name=&quot;OverlayContainerTransform&quot;
                          X=&quot;{Binding ElementName=OverlayContainer, Path=ActualWidth}&quot; 
                          Y=&quot;0&quot;/&gt;
    &lt;/Grid.RenderTransform&gt;
  
    &lt;ContentPresenter x:Name=&quot;OverlayContent&quot; Content=&quot;{Binding Path=OverlayViewModel&quot;/&gt;
  
  &lt;/Grid&gt;
  </code></pre>
  <p>I can then dynamically set the <em>OverlayViewModel</em> property to various view models when needed and use data templates to get WPF to automatically display the correct view for the relevant view model:</p>
  <pre><code>&lt;DataTemplate DataType=&quot;{x:Type ViewModels:AuthorisatonViewModel}&quot;&gt;
      &lt;Views:AuthorisatonView/&gt;
  &lt;/DataTemplate&gt;
  </code></pre>
  <p>When I change my view model and slide on the overlay I set focus scope to the overlay focus scope (which I seem to be able to do OK with OverlayContainer.Focus), but the problem I'm having is that I can't seem to get keyboard focus to go to the first focusable element on the relevant view, whatever it may be.</p>
  <p>I thought I'd found what I needed <a href="http://julmar.com/blog/mark/?p=50" rel="nofollow noreferrer">here</a> but when using this code to walk the visual tree it seems that when passing the ContentPresenter (<em>OverlayContent</em>) into VisualTreeHelper.GetChildrenCount() that it returns no children, so it can't get down the elements within the dynamic view.</p>
  <p>I've also tried setting the <em>OverlayContainer</em> as the active focus scope and then calling:</p>
  <pre><code>OverlayContainer.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next))
  </code></pre>
  <p>but that failed to work also.</p>
  <p>All the views I am trying to display have at least 1 focusable, visible, enabled element in them.</p>
  <p>Any ideas?</p>