Dot-Net

WPF MVVM ViewModel 建構子設計模式

  • December 15, 2019

我有一個 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
   }

它甚至可以在設計時完美執行。

如果要DataContext在 XAML 中設置,可以在ViewModelctor 頂部使用它:

if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
   return;

您可以嘗試的只是DataContext在後面的程式碼中設置,看看是否能解決問題。這幾乎是完全相同的事情,但也許你的 IDE 只是在發揮作用。

DataContext = new MainViewModel();

引用自:https://stackoverflow.com/questions/2498521