2012-10-25 18 views
3

如何將CustomerRepository注入到CustomerVM視圖模型中?在我看來,一個WPF頁,我有:與WPF MVVM Unity,Generic Repository交錯

<Page.DataContext> 
    <viewModel:CustomerVM/> 
</Page.DataContext> 

但我的視圖模型構造顯然有參數傳入,

public CustomerVM(ICustomerRepository customerRepository) 
    { 
     //this._customerRepository = customerRepository; 
    } 

我得到

類型'CustomerVM'不可用作對象元素,因爲它不是 公共或未定義公共無參數構造函數或類型 轉換器。

真的很掙扎。

任何幫助表示讚賞。

+0

你能給我們提供這個錯誤的靈嗎?或代碼片段? – Danpe

+0

請參閱[這裏] [1] 我建議視圖模型定位方法 [1]:http://stackoverflow.com/questions/5830199/setting-viewmodels-property-from-xaml –

回答

1

如果您使用依賴注入,我不認爲您可以在XAML中初始化DataContext。在視圖的代碼隱藏中設置DataContext,以便Unity可以解決依賴關係。嘗試將此添加到YourView.xaml.cs中:

public YourView(CustomerVM viewModel) 
{ 
    InitializeComponent(); 

    this.DataContext = viewModel; 
} 

如果您通過Unity解析視圖,上述方法將有效。如果沒有,你還可以使用服務定位器來解決視圖模型:如果你不使用棱鏡

using Microsoft.Practices.ServiceLocation; 

public YourView() 
{ 
    InitializeComponent(); 

    this.DataContext = ServiceLocator.Current.GetInstance<CustomerVM>(); 
} 

您可能還需要添加某處你的註冊碼來設置服務定位如下:

ServiceLocator.SetLocatorProvider(new ServiceLocatorProvider(() => new UnityServiceLocator(_unityContainer))); 
+0

由於儘快導航到視圖,並將視圖模型作爲參數get Object引用未設置爲對象的實例。 ?????即使我有unitycontainer註冊CustomerVM的實例? – CheGuevarasBeret

+0

請參閱我上面關於使用ServiceLocator來解析CustomerVM的編輯。如果這不起作用,您可以發佈您的Unity註冊碼嗎? –

+0

嗨邁克,開發機器不在這裏,但在我的app.xaml..cs我有覆蓋啓動和代碼如下:UnityContainer容器=新的UnityContainer容器(); container.registertype (); container.registertype ();這看起來是對的嗎?乾杯 – CheGuevarasBeret