Click here to Skip to main content
12,304,652 members (63,618 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4K views
1 bookmarked
Posted

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

, 22 Nov 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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())
{
  ...
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Morten Nilsen
Norway Norway
No Biography provided

You may also be interested in...

Comments and Discussions

 
Generalwww clothing2shoes com Abercrombie & Fitch Coogi Fashion ... Pin
bagsshoes2822-Nov-10 23:23
memberbagsshoes2822-Nov-10 23:23 
GeneralVery Nice Article Pin
sohanmohan22-Nov-10 19:29
membersohanmohan22-Nov-10 19:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160530.1 | Last Updated 22 Nov 2010
Article Copyright 2010 by Morten Nilsen
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid