【发布时间】:2010-03-23 08:50:37
【问题描述】:
我有一个 WPF 主窗口:
<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 是这样的:
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; }
现在的问题是,在设计器模式下我看不到我的MainViewModel,它突出显示它说它无法创建MainViewModel 的实例。它正在连接到数据库。这就是为什么(当我评论代码时问题就解决了)。
但我不希望那样。关于这方面的最佳实践的任何解决方案?
以及为什么在使用 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
}
它甚至可以在设计时完美执行。
【问题讨论】: