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

  • Microsoft Opens Up Old Win32 APIs to C# and Rust, More Languages to Come

    Microsoft is opening up old Win32 APIs long used for 32-bit Windows programming, letting coders use languages of their choice instead of the default C/C++ option.

  • Project Oqtane Provides Blazor-Based Modern App Framework

    The .NET Foundation recently shined a spotlight on Project Oqtane, a modern application framework for Blazor, Microsoft's red-hot open source project that enables web development in C#.

  • Radzen Open Sources 60+ Blazor Components

    Radzen, a development tooling vendor that provides third-party components for .NET coders, open sourced its controls for Blazor, Microsoft's red-hot open source project that enables web development in C#.

  • Customize Your Own Audio Test Cues in Visual Studio 2019 v16.9 Preview 3

    Yes, developers can be alerted to a failed test with a fart sound.

Upcoming Events