WPF and Inversion of Control: Listing 1.

Assigning the DataContext to the ViewModel.

private void AssignViewModel(object component, object[] arguments)
{
  var frameworkElement = component as FrameworkElement;
  if (frameworkElement == null || arguments == null)
  {
    return;
  }
 
  var vm = arguments.Where(a => a is IViewModel).FirstOrDefault();
  if (vm != null)
  {
    frameworkElement.DataContext = vm;
  }
}

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.