1

我是 stackoverflow 的新手,对 WPF 来说相对较新。

我已经阅读了六本重要的模式和最佳实践(以及这里的许多帖子),但似乎找不到我正在寻找的解决方案。

我的问题:WPF / .Net 4 / C# 我有一个文本处理器(类型为Editor E),可以一次加载一个 Document (类型为Document D)(存储为Editor.CurrentDocument)。几个 UI 控件绑定到Document的属性(所有依赖属性),例如Document.TitleDocument.DateLastModification

现在我希望能够切换实际的 Document 实例,而不必取消和重新挂钩所有事件处理程序。所以我猜 Editor.CurrentDocument 属性在切换其实现时必须以某种方式保持其实例。

我试图创建一个直接从 Document 继承并使用 Singleton 模式的SingleInstanceDocument类。但是后来我找不到将任何 Document 实例注入 SingleInstanceDocument 而不必在内部重新映射所有属性的方法。

我是否以某种方式被误导或错过了这里的重点?如果 SingleInstanceDocument 方法是一个可行的解决方案,有什么方法可以使用反射将所有可用的依赖属性从内部 Document 自动重新映射到外部 SingleInstanceDocument 外壳?

非常感谢!

附录

事实证明,通过在 CurrentDocument 宿主对象上实现INotifyPropertyChanged,WPF/.NET 已经提供了此处所需的功能。因此,更改当前文档会导致 UI 相应地更新其绑定控件。我为所有的混乱感到抱歉。

4

1 回答 1

0

首先,学习一些基本的 MVVM 模式。基本上在 WPF-MVVM 中只使用 ObservableCollection 和INotifyPropertyChanged 接口

这种类型的集合实现了观察者模式,当您添加/删除或“选择”当前项目时通知 UI(视图)更新。

//in main ViewModel
private Ducument _currentDocument;

public Document CurrentDocument 
{ 
    get { return _currentDocument; }
    set
    {
        _currentDocument = value;
        NotifyPropertyChanged("CurrentDocument");
    }
}

//stored all loaded documents as collection.
public ObservableCollection<Document> Documents { get; set; } 

已选择绑定 - 当前项目。

<ListBox ItemsSource="{Binding Path=Documents}" SelectedItem="{Binding Path=CurrentDocument}" DisplayMemberPath="Title">
    <!-- //all Document.Title as listitem -->
</ListBox>
<!--// Editor's View -->
<ContentControl DataContext="{Binding Path=CurrentDocument}"></ContentControl>
于 2012-04-30T09:11:48.597 回答