WPF and Inversion of Control: Listing 6.

Passing a WPF window reference to the ViewModel.

private void AssignParentView(FrameworkElement frameworkElement, object dataContext)
{
  var view = frameworkElement as IView;
  if (view == null)
  {
    return;
  }

  var viewProp = dataContext.GetType()
  .GetProperties(BindingFlags.Public | BindingFlags.Instance)
  .Where(p => p.CanWrite && typeof (IView).IsAssignableFrom(p.PropertyType))
  .FirstOrDefault();

  if (viewProp != null)
  {
    viewProp.SetValue(dataContext, frameworkElement, null);
  }
}

About the Author

Patrick Steele is a senior .NET developer with Billhighway in Troy, Mich. A recognized expert on the Microsoft .NET Framework, he’s a former Microsoft MVP award winner and a presenter at conferences and user group meetings.

comments powered by Disqus

Featured

  • Black White Wave IMage

    New Azure AI VMs Immediately Claim Top500 Supercomputer Rankings

    Visual Studio coders who dabble in artificial intelligence projects can now take advantage of new Azure virtual machines (VMs) featuring 80 GB NVIDIA GPUs that immediately claimed four spots on the TOP500 supercomputers list, Microsoft said.

  • Colorful Night IMage

    Auto Completions Speed Up in Java on Visual Studio Code

    Java jockeys using Microsoft's Visual Studio Code editor will see faster code completions thanks to a new language server.

  • New Toolkit for Writing Visual Studio Extensions (And Where to Find Extensions)

    Microsoft details a new Extensibility Essentials toolkit for VS 2022 and explains where to find your favorite tools.

  • New TypeScript 4.5 Improves Asynchronous Programming

    TypeScript 4.5 has shipped with a new Awaited type and Promise improvements for enhancing asynchronous programming in Microsoft's popular take on JavaScript that adds statically checked types.

Upcoming Events