• WPF调用webapi并展示数据(一):WPF页面的构建


    有错误欢迎大家给我指正

    本项目为WPF+Prism+net6.0

    RestSharp调用API

    UI为MaterialDesignThemes

    EF Core自动生成数据库

    效果展示:

    项目启动后点击待办事项进入数据展示页

    源码地址:绎Ronion/WPF.ToDo (gitee.com)

    1.准备

    1.1创建WPF项目

    1.2 创建完成后,下载Nuget包:Prism.DryIoc、MaterialDesignThemes、Newtonsoft.Json

    2.App.xaml的修改

    2.1 添加

    1. xmlns:prism="http://prismlibrary.com/"
    2. xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"

    2.2 把最外层的Application标签改为prism:PrismApplication

    2.3 引入资源文件,并删除StartupUri(不删除会重复加载,导致出现两个窗体)

    App.xaml全文如下:

    1. <prism:PrismApplication x:Class="ToDoDemo.App"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:local="clr-namespace:ToDoDemo"
    5. xmlns:prism="http://prismlibrary.com/"
    6. xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">
    7. <Application.Resources>
    8. <ResourceDictionary>
    9. <ResourceDictionary.MergedDictionaries>
    10. <materialDesign:BundledTheme BaseTheme="Dark" PrimaryColor="DeepPurple" SecondaryColor="Lime" />
    11. <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
    12. ResourceDictionary.MergedDictionaries>
    13. ResourceDictionary>
    14. Application.Resources>
    15. prism:PrismApplication>

    3.主页面

    3.1 新建文件夹Views,在文件夹内新建窗口MainView.xaml(删除默认窗口)

    3.2引用MaterialDesignThemes和Prism

    1. xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    2. xmlns:prism="http://prismlibrary.com/"

    主页面最终引用:

    WindowStartupLocation="CenterScreen" 启动时居中
    WindowStyle="None"隐藏边框
    AllowsTransparency="True"隐藏白边

    1. <Window x:Class="ToDoDemo.Views.MainView"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:ToDoDemo.Views"
    7. xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    8. xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    9. xmlns:prism="http://prismlibrary.com/"
    10. xmlns:ext="clr-namespace:ToDoDemo.Extensions"
    11. mc:Ignorable="d"
    12. Height="450" Width="800"
    13. WindowStyle="None"
    14. AllowsTransparency="True"
    15. WindowStartupLocation="CenterScreen">
    16. Window>

    3.3 这里设定为,点击导航栏的待办事项跳转到待办页,所以会用到UI组件的部分组件,会直接引用,我会把所有的代码贴出来

    UI的源码地址,感兴趣的可以详细了解:

    Releases · MaterialDesignInXAML/MaterialDesignInXamlToolkit (github.com)

    3.4在App.xaml的下添加样式资源

    1. <Style x:Key="MyListBoxItemStyle" TargetType="ListBoxItem">
    2. <Setter Property="MinHeight" Value="40" />
    3. <Setter Property="Template">
    4. <Setter.Value>
    5. <ControlTemplate TargetType="{x:Type ListBoxItem}">
    6. <Grid>
    7. <Border x:Name="borderHeader" />
    8. <Border x:Name="border" />
    9. <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
    10. Grid>
    11. <ControlTemplate.Triggers>
    12. <Trigger Property="IsSelected" Value="True">
    13. <Setter TargetName="borderHeader" Property="BorderThickness" Value="4,0,0,0" />
    14. <Setter TargetName="borderHeader" Property="BorderBrush" Value="{DynamicResource PrimaryHueLightBrush}" />
    15. <Setter TargetName="border" Property="Background" Value="{DynamicResource PrimaryHueLightBrush}" />
    16. <Setter TargetName="border" Property="Opacity" Value="0.2" />
    17. Trigger>
    18. <Trigger Property="IsMouseOver" Value="True">
    19. <Setter TargetName="border" Property="Background" Value="{DynamicResource PrimaryHueLightBrush}" />
    20. <Setter TargetName="border" Property="Opacity" Value="0.2" />
    21. Trigger>
    22. ControlTemplate.Triggers>
    23. ControlTemplate>
    24. Setter.Value>
    25. Setter>
    26. Style>

    3.5创建文件夹Common,在里面创建新文件MenuBar

    1. ///
    2. /// 系统导航菜单实体类
    3. ///
    4. public class MenuBar : BindableBase
    5. {
    6. private string icon;
    7. ///
    8. /// 菜单图标
    9. ///
    10. public string Icon
    11. {
    12. get { return icon; }
    13. set { icon = value; }
    14. }
    15. private string title;
    16. ///
    17. /// 菜单名称
    18. ///
    19. public string Title
    20. {
    21. get { return title; }
    22. set { title = value; }
    23. }
    24. private string nameSpace;
    25. ///
    26. /// 菜单命名空间
    27. ///
    28. public string NameSpace
    29. {
    30. get { return nameSpace; }
    31. set { nameSpace = value; }
    32. }
    33. }

    3.6创建文件夹Extensions,在里面创建新文件PrismManager

    1. public static class PrismManager
    2. {
    3. ///
    4. /// 首页区域
    5. ///
    6. public static readonly string MainViewRegionName = "MainViewRegion";
    7. ///
    8. /// 设置页区域
    9. ///
    10. public static readonly string SettingsViewRegionName = "SettingsViewRegion";
    11. }

    3.7创建文件夹ViewModels,在里面创建新文件MainViewModel

    1. public class MainViewModel : BindableBase
    2. {
    3. public MainViewModel(IRegionManager regionManager)
    4. {
    5. MenuBars = new ObservableCollection();
    6. CreateMenuBar();
    7. NavigateCommand = new DelegateCommand(Navigate);
    8. this.regionManager = regionManager;
    9. }
    10. private void Navigate(MenuBar obj)
    11. {
    12. if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))
    13. return;
    14. regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(obj.NameSpace, back =>
    15. {
    16. });
    17. }
    18. public DelegateCommand NavigateCommand { get; private set; }//做导航
    19. private readonly IRegionManager regionManager;
    20. //ObservableCollection是一个动态属性集合,可以动态地添加和删除其中的元素
    21. private ObservableCollection menuBars;//动态属性集合
    22. public ObservableCollection MenuBars
    23. {
    24. get { return menuBars; }
    25. set
    26. {
    27. menuBars = value;
    28. RaisePropertyChanged();//通知属性值发生了变化
    29. }
    30. }
    31. void CreateMenuBar()
    32. {
    33. MenuBars.Add(new MenuBar() { Icon = "Home", Title = "首页", NameSpace = "IndexView" });
    34. MenuBars.Add(new MenuBar() { Icon = "NotebookOutline", Title = "待办事项", NameSpace = "ToDoView" });
    35. MenuBars.Add(new MenuBar() { Icon = "NotebookPlus", Title = "备忘录", NameSpace = "MemoView" });
    36. MenuBars.Add(new MenuBar() { Icon = "Cog", Title = "设置", NameSpace = "SettingsView" });
    37. }
    38. }

    3.8在Views创建ToDoView,在ViewModels创建ToDoViewModel

    3.9在App.xaml.cs注册,注意把Application改为PrismApplication

    1. public partial class App : PrismApplication
    2. {
    3. protected override Window CreateShell()
    4. {
    5. return Container.Resolve();
    6. }
    7. protected override void RegisterTypes(IContainerRegistry containerRegistry)
    8. {
    9. containerRegistry.RegisterForNavigation();
    10. }
    11. }

    3.10主页的全部代码如下

    1. <Window x:Class="ToDoDemo.Views.MainView"
    2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    4. xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    5. xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    6. xmlns:local="clr-namespace:ToDoDemo.Views"
    7. xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
    8. xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
    9. xmlns:prism="http://prismlibrary.com/"
    10. xmlns:ext="clr-namespace:ToDoDemo.Extensions"
    11. mc:Ignorable="d"
    12. Height="450" Width="800"
    13. WindowStyle="None"
    14. AllowsTransparency="True"
    15. WindowStartupLocation="CenterScreen">
    16. <materialDesign:DialogHost DialogTheme="Inherit" Identifier="RootDialog"
    17. SnackbarMessageQueue="{Binding ElementName=MainSnackbar, Path=MessageQueue}">
    18. <materialDesign:DrawerHost x:Name="drawerHost"
    19. IsLeftDrawerOpen="{Binding ElementName=MenuToggleButton, Path=IsChecked}">
    20. <materialDesign:DrawerHost.LeftDrawerContent>
    21. <DockPanel MinWidth="220">
    22. <ListBox ItemContainerStyle="{StaticResource MyListBoxItemStyle}"
    23. ItemsSource="{Binding MenuBars}" x:Name="menuBar">
    24. <i:Interaction.Triggers>
    25. <i:EventTrigger EventName="SelectionChanged">
    26. <i:InvokeCommandAction Command="{Binding NavigateCommand}"
    27. CommandParameter="{Binding ElementName=menuBar,Path=SelectedItem}"/>
    28. i:EventTrigger>
    29. i:Interaction.Triggers>
    30. <ListBox.ItemTemplate>
    31. <DataTemplate>
    32. <StackPanel Background="Transparent" Orientation="Horizontal">
    33. <materialDesign:PackIcon Margin="15,0" Kind="{Binding Icon}"/>
    34. <TextBlock Text="{Binding Title}" Margin="10,0"/>
    35. StackPanel>
    36. DataTemplate>
    37. ListBox.ItemTemplate>
    38. ListBox>
    39. DockPanel>
    40. materialDesign:DrawerHost.LeftDrawerContent>
    41. <DockPanel>
    42. <materialDesign:ColorZone Padding="16" x:Name="ColorZone"
    43. materialDesign:ElevationAssist.Elevation="Dp4"
    44. DockPanel.Dock="Top" Mode="PrimaryMid">
    45. <DockPanel LastChildFill="True">
    46. <StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
    47. <Button x:Name="btnMin" Content="—" Style="{StaticResource MaterialDesignFlatMidBgButton}" />
    48. <Button x:Name="btnMax" Content="☐" Style="{StaticResource MaterialDesignFlatMidBgButton}" />
    49. <Button x:Name="btnClose" Content="✕" Style="{StaticResource MaterialDesignFlatMidBgButton}" />
    50. StackPanel>
    51. <StackPanel Orientation="Horizontal">
    52. <ToggleButton x:Name="MenuToggleButton" IsChecked="False"
    53. AutomationProperties.Name="HamburgerToggleButton"
    54. Style="{StaticResource MaterialDesignHamburgerToggleButton}" />
    55. StackPanel>
    56. DockPanel>
    57. materialDesign:ColorZone>
    58. <ContentControl prism:RegionManager.RegionName="{x:Static ext:PrismManager.MainViewRegionName}" />
    59. DockPanel>
    60. materialDesign:DrawerHost>
    61. materialDesign:DialogHost>
    62. Window>

    3.6在MainView.xaml.cs内,添加各个按钮的事件

    1. public MainView()
    2. {
    3. InitializeComponent();
    4. //点击导航栏后收回
    5. menuBar.SelectionChanged += (s, e) =>
    6. {
    7. drawerHost.IsLeftDrawerOpen = false;
    8. };
    9. //最小化
    10. btnMin.Click += (s, e) => { this.WindowState = WindowState.Minimized; };
    11. //最大化
    12. btnMax.Click += (s, e) =>
    13. {
    14. if (this.WindowState == WindowState.Maximized)
    15. this.WindowState = WindowState.Normal;
    16. else
    17. this.WindowState = WindowState.Maximized;
    18. };
    19. //关闭
    20. btnClose.Click += async (s, e) =>
    21. {
    22. this.Close();
    23. };
    24. //拖动窗口
    25. ColorZone.MouseMove += (s, e) =>
    26. {
    27. if (e.LeftButton == MouseButtonState.Pressed)
    28. this.DragMove();
    29. };
    30. //双击放大/缩小
    31. ColorZone.MouseDoubleClick += (s, e) =>
    32. {
    33. if (this.WindowState == WindowState.Normal)
    34. this.WindowState = WindowState.Maximized;
    35. else
    36. this.WindowState = WindowState.Normal;
    37. };
    38. }

     第二篇:WPF调用webapi并展示数据(二):类库实体类的构建-CSDN博客

  • 相关阅读:
    RDMA Shared Receive Queue(四)
    买家的诉求决定你的产品卖点
    基于JAVA物业管理系统计算机毕业设计源码+数据库+lw文档+系统+部署
    Django-(4)
    【python】python面向对象——类的使用
    如何发布一个 NPM 包
    甲骨文发布适用于 MongoDB 的 Oracle Database API;Chrome 和 Edge 互相“拉踩”;树莓派驱动程序现可在 Android 上运行 | 开源日报
    蓝桥杯(1):python排序
    记录--编写一个能运行的简易ko
    微信小程序给 thinkphp后端发送请求出现错误 Wrong number of segments 问题的解决 【踩坑记录】
  • 原文地址:https://blog.csdn.net/Ronion123/article/details/136320107