2011-08-12 45 views
10

我正在創建一個應用程序,其中應顯示一組控件之前攔截和翻譯對象列表。爲此,我創建了一個類型爲ObservableCollection的DependencyProperty(BackupEntry是定義關於數據庫的信息的定製類)。我想要發生的是該控件將綁定到MVVM中的ObservableCollection。這個集合可以用來初始加載控件。然後,當通過控制接口添加一個條目時,它應該被添加到內部ObservableCollection中,該內部定義爲DependencyProperty,並在綁定後顯示在MVVM的集合中。下面是我使用的代碼:ObservableCollection作爲DependencyProperty

protected ObservableCollection<BackupEntry> _BackupItems = new ObservableCollection<BackupEntry>(); 

public static readonly DependencyProperty BackupItemsProperty = DependencyProperty.Register("BackupItems", typeof(ObservableCollection<BackupEntry>), typeof(ExplorerWindow)); 

public ObservableCollection<BackupEntry> BackupItems 
{ 
    get { return (ObservableCollection<BackupEntry>)GetValue(BackupItemsProperty); } 
    set { SetValue(BackupItemsProperty, value); } 
} 

public ExplorerWindow() 
{ 
    DefaultStyleKeyProperty.OverrideMetadata(typeof(ExplorerWindow), new FrameworkPropertyMetadata(typeof(ExplorerWindow))); 
    SetValue(BackupItemsProperty, _BackupItems); 
    _BackupItems.CollectionChanged += new NotifyCollectionChangedEventHandler(BackupItems_CollectionChanged); 
} 

void BackupItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
{ 
    throw new NotImplementedException(); 
} 

而且在測試程序:

<my:ExplorerWindow Name="ew" HorizontalAlignment="Left" VerticalAlignment="Top" Width="503" Height="223" BackupItems="{Binding BackupListItems}" /> 

我在我的測試應用程序創建的屏幕上的按鈕。當它被點擊時,一個項目被添加到BackupListItems。 BackupItems_CollectionChanged永遠不會被調用,並且新項目不會顯示在我的控件中的集合中。我完全偏離這裏嗎?我需要做些什麼來完成這項工作?

+0

上述代碼是您的ViewModel嗎?如果是這樣,你爲什麼使用依賴對象而不是屬性 –

+0

不,上面的代碼是我的控制代碼隱藏。在列表中輸入的數據與正在用於顯示的控件之間沒有直接關係。 DependencyObject是爲了公開列表,以便它可以被綁定和傳入和傳出控件。 –

回答

9

您應該遵循this question中給出的模式。您需要在PropertyChanged處理程序中訂閱CollectionChanged事件,如上面的鏈接所示。

+0

完美的工作。感謝您的快速回復。 –

-1

集合更改事件僅訂閱了您在ExplorerWindow構造函數中設置的BackupItems的默認值。然後,將默認值替換爲viewmodel中的集合 - 您尚未訂閱該集合。每次設置屬性時都需要訂閱collection。您可以使用接受PropertyMetadata的DependencyProperty.Register的重載,並在屬性更改時提供回調。這是一個粗略的草圖 - 沒有編譯它,但應指向正確的方向。

public static readonly DependencyProperty BackupItemsProperty = DependencyProperty.Register(
    "BackupItems", 
    typeof(ObservableCollection<BackupEntry>), 
    typeof(ExplorerWindow), 
    OnBackupItemsChanged); 

private void OnBackupItemsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) 
{ 
    var old = (ObservableCollection<BackupEntry>)e.OldValue; 
    if (old != null) 
    { 
     old.CollectionChanged -= BackupItems_CollectionChanged; 
    } 
    ((ObservableCollection<BackupEntry>)e.NewValue).CollectionChanged += BackupItems_CollectionChanged; 
} 

void BackupItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) 
{ 
    throw new NotImplementedException(); 
} 
+0

它不起作用。 'DependencyProperty'是一個靜態的,但是'OnBackupItemsChanged'不是。 –

相關問題