# 個人博客-推薦文章載入優化 # 前言 隨著博客文章越來越多,那麼推薦的文章也是越來越多,之前推薦文章是只推薦8篇,但是我感覺有點少,然後也是決定加一個載入按鈕,也是類似與分頁的效果,點擊按鈕可以繼續載入8篇文章。 # 我的實現思路 同樣使用`X.PagedList`組件去實現分頁效果,通過Nug ...
Prism導航
-
新建視圖
UserControl
及其ViewModel,被跳轉的視圖的VM需要實現INavigationAware
-
在
App.xaml.cs
中註冊視圖及其ViewModel
// App.xaml.cs
containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>();
- 在需要放置導航內容處聲明
ContentControl
及region
占位:
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top" Margin="5" >
<Button Command="{Binding NavigateCommand}" CommandParameter="ViewA" Margin="5">Navigate to View A</Button>
<Button Command="{Binding NavigateCommand}" CommandParameter="ViewB" Margin="5">Navigate to View B</Button>
</StackPanel>
<ContentControl prism:RegionManager.RegionName
="{x:Static ext:PrismManager.MainViewRegionName}" />
</DockPanel>
Region
是Prism
內部的一個數據結構,它的Name
屬性是此處在XAML中聲明的RegionName
(詳見下節)。
- 在需要進行導航行為的ViewModel處註入並使用,如:
// ViewModel
public DelegateCommand<string> NavigateCommand { get; private set; }
public MainWindowViewModel(IRegionManager regionManager)
{
_regionManager = regionManager;
NavigateCommand = new DelegateCommand<string>(Navigate);
}
private void Navigate(string navigatePath)
{
if (navigatePath != null)
_regionManager.RequestNavigate("ContentRegion", navigatePath);
}
RegionManager
-
Region
對應的是在XAML中聲明的ContentControl
的附加屬性prism:RegionManager.RegionName
-
RegionManager
管理著所有Region
對象,這些Region
對象被裝到RegionCollection
中的列表屬性 -
RegionManager
中的3個方法UpdateRegions
在PrismApplicationBase#Initialize
中被調用,它會根據在XAML中聲明的RegionName
創建Region
對象RequestNavigate
在需要導航時調用,調用它時會根據 regionName 去 regionCollection 中找到對應的Region
對象,並通過集合ActiveViews
找到滿足條件的 View 實例從而進行ContentControl
內容的切換- 可以主動調用
RegisterViewWithRegion
進行Region
和視圖的註冊
在進入視圖時導航
由於 View 和 ViewModel 的初始化 MvvmHelpers.AutowireViewModel(shell);
先於 Region
的初始化RegionManager.UpdateRegions();
,因此在View和ViewModel初始化時找不到相應的 Region
對象。
// PrismApplicationBase.cs
protected virtual void Initialize()
{
// ...
if (shell != null)
{
MvvmHelpers.AutowireViewModel(shell);
RegionManager.SetRegionManager(shell, _containerExtension.Resolve<IRegionManager>());
RegionManager.UpdateRegions();
InitializeShell(shell);
}
// ...
在視窗初始化時,Initilized
事件發生時數據綁定未完成;Loaded
事件發生時數據綁定已經完成。
因此,可以手動註冊 Region
;也可以在數據綁定結束之後訪問 Region
。
方法1 Loaded事件
private void Window_Loaded(object sender, RoutedEventArgs e)
{
regionManager.RequestNavigate("ContentRegion", "ViewA");
}
方法2 手動註冊 Region
// App.xaml.cs
protected override void Initialize()
{
base.Initialize();
var regionManager = Container.Resolve<IRegionManager>();
regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA));
}
// ViewModel
public MainWindowViewModel(IRegionManager regionManager)
{
regionManager.RequestNavigate("ContentRegion", "ViewA");
}
方法3 Dispatcher
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
{
regionManager.RequestNavigate("ContentRegion", "ViewA");
}));