我在包含Xceed PropertyGrid的MVVM應用程序中使用Ninject。 PropertyGrid中應使用自定義的ItemSource爲當前與屬性定義了一個特殊的屬性:PropertyGrid自定義Itemsource和依賴注入
[ItemSource(GetType(SomeObjectItemSource)]
的SomeObjectItemSource.GetValues看起來像這一點,需要對與Ninject
Public Function GetValues() As ItemCollection Implements IItemsSource.GetValues
Fetch RootObject from Ninject Kernel
Extract a list of SomeObject from RootObject and Return
End Function
隨着創建的對象訪問PropertyGrid不是由Ninject創建的,Ninject在內部使用Activator.CreateInstance而沒有任何可選的構造函數參數,因爲我無法傳遞對Ninject內核或RootObject的引用,所以此方法失敗。
注意:PropertyGrid的來源看起來像這樣。 Activate.CreateInstance將能夠使用構造函數,但它不是以這種方式實現的。
private System.Collections.IEnumerable CreateItemsSource()
{
var instance = Activator.CreateInstance(_attribute.Type);
return (instance as IItemsSource).GetValues();
}
替代地將可能使用利用ITypeEditor和結合編輯器來創建該PropertyGrid中的實例的屬性的自定義類型的編輯器。該方法是在這裏建議:http://wpftoolkit.codeplex.com/discussions/351513,看起來像:
Public Class SomeObjectTypeEditor
Implements ITypeEditor
Public Function ResolveEditor(propertyItem As PropertyItem) As FrameworkElement
Dim box As New ComboBox() With { _
.DisplayMemberPath = "SomeObject" _
}
Dim itemSourcebinding = New Binding("") With { _
.Source = MainWindow.ListOfSomeObject , _
.ValidatesOnExceptions = True, _
.ValidatesOnDataErrors = True, _
.Mode = BindingMode.OneWay _
}
End Function
End Class
如果我想堅持我避免後面的代碼是唯一可行的辦法,我看到的是使用上MainWindow.ListOfSomeObject財產注射。然而,這看起來並不適合我。
我也猜測這種情況也會出現在不同的控件中。是否有解決所有WPF控件的這些問題的通用抽象方法?