我正在創建一個應用程序,其中應顯示一組控件之前攔截和翻譯對象列表。爲此,我創建了一個類型爲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永遠不會被調用,並且新項目不會顯示在我的控件中的集合中。我完全偏離這裏嗎?我需要做些什麼來完成這項工作?
上述代碼是您的ViewModel嗎?如果是這樣,你爲什麼使用依賴對象而不是屬性 –
不,上面的代碼是我的控制代碼隱藏。在列表中輸入的數據與正在用於顯示的控件之間沒有直接關係。 DependencyObject是爲了公開列表,以便它可以被綁定和傳入和傳出控件。 –