关于wpf:什么时候应该使用UserControl而不是Page?

When should I use a UserControl instead of a Page?

我注意到许多WPF MVVM框架似乎都避免使用NavigationWindow和Page控件,而倾向于使用嵌套的UserControls组成页面。

NavigationWindow和Page提供了在日记中启用前后导航的简便方法,并提供了在各页之间传递数据的简便方法。我见过的大多数MVVM框架都以各种方式重新实现了这些功能。

是否有避免使用NavigationWindow和Page的特定原因?


"NavigationWindow does not store an
instance of a content object in
navigation history. Instead,
NavigationWindow creates a new
instance of the content object each
time it is navigated to by using
navigation history. This behavior is
designed to avoid excessive memory
consumption when large numbers and
large pieces of content are being
navigated to. Consequently, the state
of the content is not remembered from
one navigation to the next. However,
WPF provides several techniques by
which you can store a piece of state
for a piece of content in navigation
history...."

http://msdn.microsoft.com/zh-cn/library/system.windows.navigation.navigationwindow.aspx


我刚刚发现UserControls和Pages之间的另一个区别:Pages不能用作DataTemplates。

例如,如果您正在使用MVVM样式创建应用程序,则可能希望它能够正常工作:

1
2
3
    <DataTemplate DataType="{x:Type ViewModels:ProjectDashboardViewModel}">
        <Views:ProjectDashboardView />
    </DataTemplate>

但是如果ProjectDashboardView是一个Page,它将失败。


我刚刚在Paul Stovell的网站上找到了一些其他有关WPF NavigationWindow和Page的有趣信息。

他对NavigationWindow类有以下说法:

WPF includes a class called NavigationWindow, which is essentially a Window which also doubles as a Frame, by implementing most of the same interfaces. It sounds useful at first, but most of the time you need more control over the Window, so I've never had any need to use this class. I am just pointing it out for the sake of completeness, though your mileage may vary.

请参阅他关于WPF导航以及在编写Magellan WPF框架时遇到的Magellan和WPF页面管理问题的深入文章。


好吧,您仍将使用用户控件来创建可重用的子组件,但是对于应用程序体系结构,这实际上取决于用例。如果您要构建典型的Web应用程序,则可以使用Business / Navigation App。如果您正在编写游戏,则不需要太多。同样,如果您正在做类似交互式广告或媒体播放器的操作。