I'm learning WPF, MVVM Light and the ViewModelLocator pattern and running into difficulties with my main window's data context.
public class ViewModelLocator
{
public ViewModelLocator()
{
var mainModel = new MainModel();
Main = new MainViewModel(mainModel);
}
public MainViewModel Main { get; private set; }
public static ViewModelLocator Instance
{
get { return Application.Current.Resources["Locator"] as ViewModelLocator; }
}
}
and in my app.xaml:
<Application.Resources>
<viewModels:ViewModelLocator x:Key="Locator" />
</Application.Resources>
When I set the data context in my main window using:
DataContext="Binding Main, Source={StaticResource Locator}"
it compiles but all of MainViewModel's properies I bind to elsewhere in the xaml show up red with tooltip "cannot resolve symbol". I thought I could get around this by also specifying a designer-only data context:
<Window x:Class="WPFDemo.Windows.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:converters="clr-namespace:WPFDemo.Converters"
xmlns:local="clr-namespace:WPFDemo"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:models="clr-namespace:WPFDemo.Models"
xmlns:viewModels="clr-namespace:WPFDemo.ViewModels"
Title="MainWindow" Height="350" Width="525"
DataContext="Binding Main, Source={StaticResource Locator}"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance, Type=viewModels:MainViewModel,
IsDesignTimeCreatable=True}">
but the compiler doesn't like that last line ("The character ',' is unexpected at this position", referrring to the first comma). Note I'm not using ExpressionBlend, but I thought I heard in a course that this line would enable VisualStudio designer as well:
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
How do I use a ViewModelLocator while still enabling Visual Studio to recognize bound properties at design time?
Using the default data context should also work in design time:
If not, try to compile the proyect and check out again. You can manage the properties values that you want to show in design time by using the
IsInDesignMode
property that theMvvmLight Toolkit
provides. By default theMainViewModel
's constructor looks like this:Hope this helps...
The last line will work nicely if you remove the comma after
d:DesignInstance
: