WPF MVVM视图模型构造的designMode

问题描述:

我有一个主要的WPF窗口:

I've got a main wpf window:

<Window x:Class="NorthwindInterface.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ViewModels="clr-namespace:NorthwindInterface.ViewModels" Title="MainWindow" Height="350" Width="525">
    <Window.DataContext>
        <ViewModels:MainViewModel />
    </Window.DataContext>
    <ListView ItemsSource="{Binding Path=Customers}">

    </ListView>
</Window>

而MainViewModel是这样的:

And the MainViewModel is this:

class MainViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged = delegate { };

    public MainViewModel()
    {
        Console.WriteLine("test");
        using (NorthwindEntities northwindEntities = new NorthwindEntities())
        {
            this.Customers = (from c in northwindEntities.Customers
                              select c).ToList();
        }
    }

    public List<Customer> Customers { get;private  set; }

现在的问题是,在designermode我看不到我的MainViewModel,它强调它说,它不能创建MainViewModel的一个实例。它连接到数据库。这就是为什么(当我评论了code中的问题解决)。

Now the problem is that in designermode I can't see my MainViewModel, it highlights it saying that it can't create an instance of the MainViewModel. It is connecting to a database. That is why (when I comment the code the problem is solved).

但我不希望出现这种情况。解决这个最佳做法的任何解决方案?

But I don't want that. Any solutions on best practices around this?

和为什么这项工作MVVM工作时:

And why does this work when working with MVVM:

    /// <summary>
    /// Initializes a new instance of the <see cref="MainViewModel"/> class.
    /// </summary>
    public MainViewModel()
    {
        // Just providing a default Uri to use here...
        this.Uri = new Uri("http://www.microsoft.com/feeds/msdn/en-us/rss.xml");
        this.LoadFeedCommand = new ActionCommand(() => this.Feed = Feed.Read(this.Uri), () => true);
        this.LoadFeedCommand.Execute(null); // Provide default set of behavior
    }

甚至完全执行在设计时。

It even executes perfectly at design time.

这将让你看到设计师。

public MainViewModel()
{
    if (!DesignerProperties.IsInDesignTool)
    {
      Console.WriteLine("test");
      using (NorthwindEntities northwindEntities = new NorthwindEntities())
      {
        this.Customers = (from c in northwindEntities.Customers
                          select c).ToList();
      }
    }
}