十年河東,十年河西,莫欺少年窮
學無止境,精益求精
實現的效果:
1、初始化Prism
1.1、項目引入如下包
1.2、按照Prism規則,項目中創建如下文件夾
Prism 規則:必須將窗體放入 Views文件夾中,窗體名稱必須以View結尾,必須將數據上下文放入ViewModels文件夾中,上下文類必須以Model結尾
另外兩個文件夾分爲存放用戶控件 及 用戶控件使用的數據類
新建窗體MainView 和 MainViewModel、新建用戶控件IndexView 和 IndexViewModel、新建用戶控件UserView 和 UserViewModel (其實用戶控件及上下文類無需遵守Prism規則)
1.3、初始化App.xaml 及 App.cs
App.cs
using Prism.DryIoc; using Prism.Ioc; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; using WpfApp.UserControls; using WpfApp.ViewModels; using WpfApp.Views; namespace WpfApp { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : PrismApplication { protected override Window CreateShell() { return Container.Resolve<MainView>(); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<IndexView, IndexViewModel>(); containerRegistry.RegisterForNavigation<UserView, UserViewModel>(); } } }
App.Xaml
<Prism:PrismApplication x:Class="WpfApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Prism="http://prismlibrary.com/" xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes" xmlns:local="clr-namespace:WpfApp" > <Application.Resources> </Application.Resources> </Prism:PrismApplication>
App.cs 中重新了二個方法,第一個方法爲設定啓動窗口,第二個方法爲註冊導航(兩個用戶控件爲填充內容)
App.xaml 中引入 Prism 命名空間,及改造根節點
2、App.xaml 引入MaterialDesign
MaterialDesign 的GitHub地址爲: https://github.com/MaterialDesignInXAML/MaterialDesignInXamlToolkit
按照文檔引入MaterialDesign,App.xaml 變更爲:
<Prism:PrismApplication x:Class="WpfApp.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:Prism="http://prismlibrary.com/" xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes" xmlns:local="clr-namespace:WpfApp" > <Application.Resources> <ResourceDictionary> <ResourceDictionary.MergedDictionaries> <materialDesign:BundledTheme BaseTheme="Light" PrimaryColor="DeepPurple" SecondaryColor="Lime" /> <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" /> </ResourceDictionary.MergedDictionaries> <!--自定義樣式 樣式名:MyListBoxItemStyle,樣式掛載:ListBoxItem--> <Style x:Key="MyListBoxItemStyle" TargetType="ListBoxItem"> <!--自定義高度--> <Setter Property="MinHeight" Value="48" /> <Setter Property="Template"> <Setter.Value> <!--影響屬性 ListBoxItem--> <ControlTemplate TargetType="{x:Type ListBoxItem}"> <Grid> <Border x:Name="borderHeader" /> <Border x:Name="border" /> <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalAlignment}"/> </Grid> <!--觸發器--> <ControlTemplate.Triggers> <!--ListBoxItem點擊時觸發--> <Trigger Property="IsSelected" Value="True"> <Setter Property="BorderThickness" TargetName="borderHeader" Value="4,0,0,0"/> <Setter Property="BorderBrush" TargetName="borderHeader" Value="{DynamicResource PrimaryHueLightBrush}" /> <Setter TargetName="border" Property="Background" Value="{DynamicResource PrimaryHueLightBrush}" /> <Setter TargetName="border" Property="Opacity" Value="0.4" /> </Trigger> <!--鼠標懸停觸發器觸發器--> <Trigger Property="IsMouseOver" Value="True"> <Setter TargetName="border" Property="Background" Value="{DynamicResource PrimaryHueLightBrush}" /> <Setter TargetName="border" Property="Opacity" Value="0.1" /> </Trigger> </ControlTemplate.Triggers> </ControlTemplate> </Setter.Value> </Setter> </Style> </ResourceDictionary> </Application.Resources> </Prism:PrismApplication>
2.1、檢測是否成功引入 MaterialDesign
在 MainView 中添加一個按鈕
<Grid> <Button Content="檢測是否成功引入" FontSize="30" Height="80" Width="280"/> </Grid>
出現如下樣式,則證明引入成功
3、改造MainView
先貼出MainView.xaml 代碼如下:
<Window x:Class="WpfApp.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp.Views" mc:Ignorable="d" xmlns:Prism="http://prismlibrary.com/" Prism:ViewModelLocator.AutoWireViewModel="True" xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes" xmlns:i="http://schemas.microsoft.com/xaml/behaviors" TextElement.Foreground="{DynamicResource MaterialDesignBody}" Background="{DynamicResource MaterialDesignPaper}" TextElement.FontWeight="Medium" FontFamily="{materialDesign:MaterialDesignFont}" TextElement.FontSize="14" WindowStyle="None" WindowStartupLocation="CenterScreen" Title="MainView" Height="768" Width="1280"> <Window.Resources> <ResourceDictionary> <!--<Style TargetType="ListBoxItem" x:Key="Ls"> <Setter Property="MinHeight" Value="40"/> <Setter Property="BorderThickness" Value="4,0,4,0"/> </Style>--> </ResourceDictionary> </Window.Resources> <materialDesign:DialogHost DialogTheme="Inherit" Identifier="RootDialog" SnackbarMessageQueue="{Binding ElementName=MainSnackbar, Path=MessageQueue}"> <materialDesign:DrawerHost x:Name="drawerHost" IsLeftDrawerOpen="{Binding ElementName=MenuToggleButton, Path=IsChecked}" Background="Transparent"> <materialDesign:DrawerHost.LeftDrawerContent> <DockPanel MinWidth="220" Background="Transparent"> <ToggleButton Margin="16" HorizontalAlignment="Right" DockPanel.Dock="Top" IsChecked="{Binding ElementName=MenuToggleButton, Path=IsChecked, Mode=TwoWay}" Style="{StaticResource MaterialDesignHamburgerToggleButton}" /> <ListBox ItemsSource="{Binding menuBars}" ItemContainerStyle="{StaticResource MyListBoxItemStyle}" x:Name="menubar"> <i:Interaction.Triggers> <i:EventTrigger EventName="SelectionChanged"> <i:InvokeCommandAction Command="{Binding ListBoxItemChangedCommand}" CommandParameter="{Binding ElementName=menubar,Path=SelectedItem}"/> </i:EventTrigger> </i:Interaction.Triggers> <ListBox.ItemTemplate> <DataTemplate> <StackPanel Orientation="Horizontal" Background="Transparent" VerticalAlignment="Center"> <materialDesign:PackIcon Kind="{Binding MenuIcon}" Margin="15,0"/> <TextBlock Text="{Binding MenuName}" Margin="10,0" FontSize="16"/> </StackPanel> </DataTemplate> </ListBox.ItemTemplate> </ListBox> </DockPanel> </materialDesign:DrawerHost.LeftDrawerContent> <DockPanel> <materialDesign:ColorZone Padding="16" x:Name="ColorZone" materialDesign:ElevationAssist.Elevation="Dp4" DockPanel.Dock="Top" Mode="PrimaryMid"> <DockPanel LastChildFill="False"> <StackPanel Orientation="Horizontal"> <ToggleButton x:Name="MenuToggleButton" AutomationProperties.Name="HamburgerToggleButton" IsChecked="False" Style="{StaticResource MaterialDesignHamburgerToggleButton}" /> <Button Margin="24,0,0,0" materialDesign:RippleAssist.Feedback="{Binding RelativeSource={RelativeSource Self}, Path=Foreground, Converter={StaticResource BrushRoundConverter}}" Command="{Binding BtnBack}" Content="{materialDesign:PackIcon Kind=ArrowLeft, Size=24}" Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}, Path=(TextElement.Foreground)}" Style="{StaticResource MaterialDesignToolButton}" ToolTip="Previous Item" Cursor="Hand" /> <Button Margin="16,0,0,0" materialDesign:RippleAssist.Feedback="{Binding RelativeSource={RelativeSource Self}, Path=Foreground, Converter={StaticResource BrushRoundConverter}}" Command="{Binding BtnForward}" Content="{materialDesign:PackIcon Kind=ArrowRight, Size=24}" Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}, Path=(TextElement.Foreground)}" Style="{StaticResource MaterialDesignToolButton}" ToolTip="Next Item" Cursor="Hand" /> <Button Margin="16,0,0,0" materialDesign:RippleAssist.Feedback="{Binding RelativeSource={RelativeSource Self}, Path=Foreground, Converter={StaticResource BrushRoundConverter}}" Command="{Binding HomeCommand}" Content="{materialDesign:PackIcon Kind=Home, Size=24}" Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}, Path=(TextElement.Foreground)}" Style="{StaticResource MaterialDesignToolButton}" ToolTip="Home" /> </StackPanel> <TextBlock Margin="20,0,0,0" HorizontalAlignment="Center" VerticalAlignment="Center" AutomationProperties.Name="Material Design In XAML Toolkit" FontSize="22" Text="Material Design In XAML Toolkit" /> <StackPanel DockPanel.Dock="Right" Orientation="Horizontal"> <TextBlock Text="hi,wpf" Margin="0 ,8,10,0" FontSize="18" Foreground="#ffc"/> <Image Source="/images/tx.jpg" Width="25" Height="25" Margin="10 0"> <Image.Clip> <EllipseGeometry RadiusX="12.5" RadiusY="12.5" Center="12.5,12.5"/> </Image.Clip> </Image> <Button x:Name="btnMin" Content="―" Margin="5 0"/> <Button x:Name="btnMax" Content="☐" Margin="5 0"/> <Button x:Name="btnClose" Content="✕" Margin="5 0"/> </StackPanel> </DockPanel> </materialDesign:ColorZone> <ContentControl Prism:RegionManager.RegionName="MainViewRegionName" /> </DockPanel> </materialDesign:DrawerHost> </materialDesign:DialogHost> </Window>
3.1、針對xaml說明如下:
<Window x:Class="WpfApp.Views.MainView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WpfApp.Views" mc:Ignorable="d" xmlns:Prism="http://prismlibrary.com/" --引入Prism命名空間 Prism:ViewModelLocator.AutoWireViewModel="True" --根據Prism規則,自動匹配數據上下文DataContext xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes" --引入MaterialDesgin 樣式庫 xmlns:i="http://schemas.microsoft.com/xaml/behaviors" --引入行爲,用於處理ListBoxItem點擊事件 TextElement.Foreground="{DynamicResource MaterialDesignBody}" --引入 MaterialDesign 顏色 Background="{DynamicResource MaterialDesignPaper}" --引入動態資源 TextElement.FontWeight="Medium" --引入MaterialDesign 字體 FontFamily="{materialDesign:MaterialDesignFont}" --引入 materialDesign 字體 TextElement.FontSize="14" --設置字號 WindowStyle="None" --去掉窗體邊框 WindowStartupLocation="CenterScreen" --啓動後,默認居中 Title="MainView" Height="768" Width="1280">
3.2、雙擊事件、最大、最小按鈕事件、拖拽事件
/// <summary> /// MainView.xaml 的交互邏輯 /// </summary> public partial class MainView : Window { public MainView() { InitializeComponent(); //最小化 btnMin.Click += (s, e) => { this.WindowState = WindowState.Minimized; }; //最大化 btnMax.Click += (s, e) => { if (this.WindowState == WindowState.Normal) { this.WindowState = WindowState.Maximized; } else { this.WindowState = WindowState.Normal; } }; //關閉事件 btnClose.Click += (s, e) => { this.Close(); }; //鼠標拖拽事件 ColorZone.MouseMove += (s, e) => { if (e.LeftButton == MouseButtonState.Pressed) { this.DragMove(); } }; //鼠標雙擊導航欄事件 ColorZone.MouseDoubleClick += (s, e) => { if (this.WindowState == WindowState.Normal) { this.WindowState = WindowState.Maximized; } else { this.WindowState = WindowState.Normal; } }; menubar.SelectionChanged += (s, e) => { drawerHost.IsLeftDrawerOpen = false; }; } }
3.3、MainViewModel如下:
using Prism.Commands; using Prism.Mvvm; using Prism.Regions; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; namespace WpfApp.ViewModels { public class MainViewModel : BindableBase { public ObservableCollection<MenuBarDto> menuBars { get; set; } public DelegateCommand<MenuBarDto> ListBoxItemChangedCommand { get; private set; } public DelegateCommand BtnBack { get; private set; } public DelegateCommand BtnForward { get; private set; } /// <summary> /// 區域管理器-跳轉相關 /// </summary> private readonly IRegionManager regionManager; /// <summary> /// 用於保存路由跳轉記錄 /// </summary> private IRegionNavigationJournal journal; public MainViewModel(IRegionManager regionManager) { CreateMenus(); this.regionManager = regionManager; ListBoxItemChangedCommand = new DelegateCommand<MenuBarDto>(GoMenuBar); BtnBack = new DelegateCommand(Back); BtnForward = new DelegateCommand(Forward); } private void GoMenuBar(MenuBarDto obj) { //參考:MainView.Xaml 中的 <ContentControl Prism:RegionManager.RegionName="MainViewRegionName" /> regionManager.Regions["MainViewRegionName"].RequestNavigate(obj.MenuPath, navigationCallback); } private void navigationCallback(NavigationResult obj) { if (obj.Result.Value) { //如果跳轉成功,則存儲跳轉記錄 journal = obj.Context.NavigationService.Journal; } } /// <summary> /// 返回上一頁 /// </summary> private void Back() { if (journal != null && journal.CanGoBack) { journal.GoBack(); } } /// <summary> /// 返回下一頁 /// </summary> private void Forward() { if (journal != null && journal.CanGoForward) { journal.GoForward(); } } private void CreateMenus() { menuBars = new ObservableCollection<MenuBarDto>(); menuBars.Add(new MenuBarDto() { MenuIcon = "Home", MenuName = "首頁", MenuPath = "IndexView" }); menuBars.Add(new MenuBarDto() { MenuIcon = "User", MenuName = "用戶管理", MenuPath = "UserView" }); menuBars.Add(new MenuBarDto() { MenuIcon = "NotebookOutline", MenuName = "備忘錄", MenuPath = "MemoView" }); menuBars.Add(new MenuBarDto() { MenuIcon = "Cog", MenuName = "設置", MenuPath = "SetingView" }); } } public class MenuBarDto { public string MenuName { get; set; } public string MenuIcon { get; set; } public string MenuPath { get; set; } } }
說明如下:
上述代碼設計 導航跳轉,導航記錄,上一頁,下一頁等功能,不懂的小夥伴這裏就不解釋了。
最終效果圖: