我正在進入MVVM,並開始與Prism框架和我的示例應用程序中我有典型的導航。其中一頁應列出一些應用程序,我想知道實施中的差異。爲了簡單起見,這裏是來自代碼中的一些小片段迄今:ObservableCollection事件傳播和MVVM中的正確用法
應用模式
public class Application : BindableBase
{
private string _commandLine;
private string _name;
private string _smallIconSource;
public string CommandLine
{
get { return _commandLine; }
set { SetProperty(ref _commandLine, value); }
}
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
public string SmallIconSource
{
get { return _smallIconSource; }
set { SetProperty(ref _smallIconSource, value); }
}
}
ApplicationPage視圖模型
public class ApplicationPageViewModel : BindableBase
{
private ObservableCollection<Application> _applicationCollection;
public ApplicationPageViewModel()
{
// load some collection entries here
}
public ObservableCollection<Application> ApplicationCollection
{
get { return _applicationCollection; }
set
{
// if (_applicationCollection != null)
// _applicationCollection.CollectionChanged -= ApplicationCollectionChanged;
SetProperty(ref _applicationCollection, value);
// if (_applicationCollection != null)
// _applicationCollection.CollectionChanged += ApplicationCollectionChanged;
}
}
}
ApplicationPage查看
<!-- ... -->
<ItemsControl ItemsSource="{Binding ApplicationCollection}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Vertical" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<!-- some kind of representation of applications -->
<Label Content="{Binding Name}" />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<!-- ... -->
在互聯網上的一些代碼示例中,特別是在SO上的一些問題中,我看到有人問是否存儲ViewModels的ObservableCollection
,而不是像我一樣存儲模型 - 我很好奇在這個時候你會選擇那些版本在另一個版本上?
而且我想知道在Application
類變化是否在ApplicationPageViewModel
類反映,或者如果我有掛接到CollectionChanged
事件(如布賴恩拉古納斯網絡研討會在哪裏見過我看到了這個技術)。
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
您的問題基本上是如何通知有關該集合在哪些項目被更改的項目。我可以想到:1)將ViewModel實例傳遞給每個項目(構造函數或其他),項目可以訂閱ViewModel的某些事件,事件由ViewModel提升(甚至通過項目)2)ViewModel處理所有更改和通知每個項目方法在收集變化)。如果你實現了'INotifyPropertyChanged'(這是你正在收聽的事件),那麼方法(1)就會出現在框中。 – Sinatr