【发布时间】:2011-04-13 10:35:37
【问题描述】:
我们 mvvm 爱好者都知道 Josh Smith mvvm 示例,以及他如何通过将存储库对象注入 customerViewModel 的构造函数来在详细客户视图中保存客户。
但是视图模型不应该知道存储库。它只是一个视图模型,没有什么必须意识到持久性等......
如果在代码隐藏中设置了我的 Action 委托 SaveDocumentDelegate,我如何在 DocumentViewModel 上注册它?实际上,我应该在 DocumentController 中订阅委托,但是如何在 DocumentController 中实例化 DocumentView 并将其设置为 Datacontext 而不是在代码隐藏中执行此操作。我唯一想到的是在窗口中使用内容控件并将其绑定到 viewModel 的类型并使用 Document UserControl 对其进行数据模板,如下所示:
<UserControl.Resources>
<DataTemplate DataType="{x:Type ViewModel:DocumentViewModel}">
<View:DocumentDetailView/>
</DataTemplate>
</UserControl.Resources>
<ContentControl Content="{Binding MyDocumentViewModel}" />
但我不想使用控件来解决我的架构问题...
xaml:(查看第一种方法)
public partial class DocumentDetailView : UserControl
{
public DocumentDetailView()
{
InitializeComponent();
this.DataContext = new DocumentViewModel(new Document());
}
}
DocumentViewModel:
public class DocumentViewModel : ViewModelBase
{
private Document _document;
private RelayCommand _saveDocumentCommand;
private Action<Document> SaveDocumentDelegate;
public DocumentViewModel(Document document)
{
_document = document;
}
public RelayCommand SaveDocumentCommand
{
get { return _saveDocumentCommand ?? (_saveDocumentCommand = new RelayCommand(() => SaveDocument())); }
}
private void SaveDocument()
{
SaveDocumentDelegate(_document);
}
public int Id
{
get { return _document.Id; }
set
{
if (_document.Id == value)
return;
_document.Id = value;
this.RaisePropertyChanged("Id");
}
}
public string Name
{
get { return _document.Name; }
set
{
if (_document.Name == value)
return;
_document.Name = value;
this.RaisePropertyChanged("Name");
}
}
public string Tags
{
get { return _document.Tags; }
set
{
if (_document.Tags == value)
return;
_document.Tags = value;
this.RaisePropertyChanged("Tags");
}
}
}
更新:
public class DocumentController
{
public DocumentController()
{
var win2 = new Window2();
var doc = new DocumentViewModel(new DocumentPage());
doc.AddDocumentDelegate += new Action<Document>(OnAddDocument);
win2.DataContext = doc;
wind2.ShowDialog();
}
private void OnAddDocument(Document doc)
{
_repository.AddDocument(doc);
}
}
你觉得这个想法怎么样?
【问题讨论】:
-
当然 Window 是由 IDialog/WindowService 获取的 :)
标签: wpf mvvm view save viewmodel