65.9K
CodeProject is changing. Read more.
Home

How to hook up a ViewModel to a window using an attached property

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0 vote)

Nov 22, 2010

CPOL
viewsIcon

9390

I also have implemented a MarkupExtension to set the DataContext, which looks like this:[MarkupExtensionReturnType(typeof(ApplicationControllerBase))]public class ApplicationDataContext : MarkupExtension{ private Type dataContextType; public ApplicationDataContext(Type...

I also have implemented a MarkupExtension to set the DataContext, which looks like this:
[MarkupExtensionReturnType(typeof(ApplicationControllerBase))]
public class ApplicationDataContext : MarkupExtension
{
	private Type dataContextType;
	public ApplicationDataContext(Type dataContextType)
	{
		this.dataContextType = dataContextType;
	}

	public ApplicationDataContext()
		: this(null)
	{
	}

	public override object ProvideValue(IServiceProvider serviceProvider)
	{
		return ApplicationControllerBase.GetController(dataContextType);
	}
}
The usage of this is quite simply;
<Grid DataContext="{vm:ApplicationDataContext app:...}">
...
</Grid>
If you set the DataContext on an an element inside rather than directly on Window, you will get your ViewModel object instanciated design-time. When doing this, you should avoid service or database calls, as they will likely throw configurationexceptions. You can detect the designer i code using this statement:
if(DesignerProperties.GetIsInDesignMode(new System.Windows.DependencyObject())
{
  ...
}