我有一個wpf TreeView,它有一個動態itemssource。用戶可以在運行時添加和刪除項目。 我錯過了一個事件,它給了我添加到treeviews itemsSource中的當前添加的UIElement。所以我想我需要切換到OnCollectionChanged。集合更改時如何獲得UIElement?
這是我有:
// MyItemViewModel is a viewmodel for a TreeViewItem
// MyCollection is bound to hte Treeview's ItemsSource
public class MyCollection : ObservableCollection<MyItemViewModel>
{
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
switch (e.Action)
{
case NotifyCollectionChangedAction.Add:
// i like to have the UIelement which was added to the collection
// (e.NewItems contains the FrameworkElement's DataContext)
break;
}
}
}
進出口以下MVVM,不如我就可以了,不想持有該視圖模型視圖的任何元素。 我喜歡在添加項目時觸發一個事件,該項目在其發件人或EventArgs中提供了新添加的UIElement。
我已經嘗試過ItemContainerGenerator類,但它在viewmodel中沒有用,因爲它需要一個UIElement控件。
我在「Drop」事件中處理添加項目。創建一個新的viemodel,它綁定到分層樹視圖數據模板。所以在「Drop」中,我有我的數據項,但我還想在新添加的項目上調用類似FrameworkElement.BringIntoView()的東西。 – deafjeff
爲了在MVVM中實現這種類型的功能(需要使用類似'BringIntoView'的事件),我們創建了'Attached Properties'。 – Sheridan
更好:我們使用附加屬性創建行爲。我想我正在走向正確的道路。 – deafjeff