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.