我将进入MVVM,并开始使用Prism框架,在我的示例应用程序中,我有典型的导航。其中一个页面应该列出几个应用程序,我想知道实现中的不同之处。为了保持简单,到目前为止,下面是代码中的一些小片段:
应用模型
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 ViewModel
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 View
<!-- ... -->
<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>
<!-- ... -->在互联网上的一些代码示例中,尤其是在这里的一些问题中,我看到人们问是否要存储ObservableCollection of ViewModels,而不是像我这样的模型--我很好奇此时您会选择哪一个版本而不是另一个版本吗?
此外,我想知道Application类中的更改是否反映在ApplicationPageViewModel类中,还是必须连接到CollectionChanged事件(正如Brian的Webinars中看到的那样)。到目前为止,我只看到CollectionChanged事件中的这个钩子用来手动调用RaiseCanExecuteChanged方法(如果DelegateCommands )是为了防止不必要的膨胀/调用(在RelayCommand的以下实现中):
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}发布于 2016-04-11 11:53:20
如果您的集合中的属性发生变化,我将使用ViewModels。如果项目上的数据没有改变,那么如果您使用VM或Model,那么它并没有真正的不同,而这正是您所喜欢的。我个人喜欢用ViewModels包装我的模型,因为我可以很容易地添加组合属性来显示,我不想直接在我的模型中使用它。
如果要在应用程序更改时对ApplicationPageViewModel执行某些操作,则必须执行以下操作
如果您只想在添加或删除应用程序时执行一些操作,则不必使用ViewModel,只需注册ObservableCollection的CollectionChanged事件
https://stackoverflow.com/questions/36547296
复制相似问题