2015-11-06 30 views
0

我試圖找到用於創建視圖模型和服務的最佳實踐(服務只會談到服務器並返回數據視圖模型)。我見過兩種不同的方法。WPF - 使用行爲實例化視圖模型和服務

  1. 使用視圖模型定位
  2. 使用行爲(我不知道這是好辦法)

對於第二種方法,你在用戶控件定義的行爲和附加事件創建一個視圖模型實例和服務實例並將它們放在一起。

protected override void OnAttached() 
    { 
     var service = Activator.CreateInstance(ServiceType) 
     var viewModel = Activator.CreateInstance(ModelType); 
     base.AssociatedObject.DataContext = viewModel; 
     base.OnAttached(); 
    } 

,並在你的用戶控件XAML

<i:Interaction.Behaviors> 
    <be:ViewModelBehavior ViewModelType="{x:Type vm:ViewModel1}" ServiceType="{x:Type serv:Service1}"/> 
</i:Interaction.Behaviors> 

這是一個良好的使用行爲,或者我應該只使用視圖模型定位模式。

+0

您的行爲與ViewModelLocator實現爲行爲無關。另外,你對ViewModelLocator的理解還不清楚。通常,它是任何組件,允許您訪問視圖模型實例並具有多種風格。 – Liero

+0

我在看的MVVM光實施視圖模型定位,你的意思是第一個方法更好? –

回答

1

你的行爲有一個顯著的缺點 - 在每個用戶控件必須指定的行爲,ViewModelType(及服務類型以及)。

你可以做到以下幾點:

<UserControl x:Class="MyApp.HomePage" .... 
      local:ViewModelLocator.AutoWireViewModel="True"> 
    ... 
</UserControl> 

當你連接的屬性設置爲true,ViewModelLocator將創建視圖模型實例,並將其分配給用戶控件的DataContext的。該ViewModelLocatator使用命名慣例來確定視圖模型的類型。在這種情況下,它可能是HomePageViewModel,因爲視圖類型爲HomePage

此方法由Prism.Mvvm庫的PRISM ViewModelLocator使用,但我建議您自行編寫,因爲它非常簡單。

它基本上是類似於您ViewModelBehavior,但再有兩點不同:

  1. 行爲是作爲附加屬性。它允許你指定樣式的行爲,所以它會被應用到使用此樣式的任何用戶控件。您無法在樣式中指定Interaction.Behaviors。

  2. 它採用的命名規則,而不是明確設置ViewModelType


關於服務,這應該作爲一個參數視圖模型進行傳遞:你可以使用IoC模式。這是描述模式的僞代碼:

public class MyViewModel(IMyService service) {...} 

//at application startup you setup the IoC container: 
IoC.Setup<IMyService>(new MyService()); 

//later 
var viewModel = IoC.GetInstance<MyViewModel>(); //MyService will be passed as to ctor 
+0

感謝您的所有答案 –