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

Ronion123 2024-07-23 08:03:06 阅读 52

有错误欢迎大家给我指正

本项目为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 添加

<code>xmlns:prism="http://prismlibrary.com/"code>

xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"code>

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

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

App.xaml全文如下:

<prism:PrismApplication x:Class="ToDoDemo.App"code>

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"code>

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"code>

xmlns:local="clr-namespace:ToDoDemo"code>

xmlns:prism="http://prismlibrary.com/"code>

xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">code>

<Application.Resources>

<ResourceDictionary>

<ResourceDictionary.MergedDictionaries>

<materialDesign:BundledTheme BaseTheme="Dark" PrimaryColor="DeepPurple" SecondaryColor="Lime" />code>

<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />code>

</ResourceDictionary.MergedDictionaries>

</ResourceDictionary>

</Application.Resources>

</prism:PrismApplication>

3.主页面

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

3.2引用MaterialDesignThemes和Prism

xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"code>

xmlns:prism="http://prismlibrary.com/"code>

主页面最终引用:

WindowStartupLocation="CenterScreen" 启动时居中

WindowStyle="None"隐藏边框

AllowsTransparency="True"隐藏白边

<code><Window x:Class="ToDoDemo.Views.MainView"code>

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"code>

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"code>

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"code>

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"code>

xmlns:local="clr-namespace:ToDoDemo.Views"code>

xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"code>

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"code>

xmlns:prism="http://prismlibrary.com/"code>

xmlns:ext="clr-namespace:ToDoDemo.Extensions"code>

mc:Ignorable="d"code>

Height="450" Width="800"code>

WindowStyle="None"code>

AllowsTransparency="True"code>

WindowStartupLocation="CenterScreen">code>

</Window>

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

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

Releases · MaterialDesignInXAML/MaterialDesignInXamlToolkit (github.com)

3.4在App.xaml的</ResourceDictionary.MergedDictionaries>下添加样式资源

<Style x:Key="MyListBoxItemStyle" TargetType="ListBoxItem">code>

<Setter Property="MinHeight" Value="40" />code>

<Setter Property="Template">code>

<Setter.Value>

<ControlTemplate TargetType="{x:Type ListBoxItem}">code>

<Grid>

<Border x:Name="borderHeader" />code>

<Border x:Name="border" />code>

<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />code>

</Grid>

<ControlTemplate.Triggers>

<Trigger Property="IsSelected" Value="True">code>

<Setter TargetName="borderHeader" Property="BorderThickness" Value="4,0,0,0" />code>

<Setter TargetName="borderHeader" Property="BorderBrush" Value="{DynamicResource PrimaryHueLightBrush}" />code>

<Setter TargetName="border" Property="Background" Value="{DynamicResource PrimaryHueLightBrush}" />code>

<Setter TargetName="border" Property="Opacity" Value="0.2" />code>

</Trigger>

<Trigger Property="IsMouseOver" Value="True">code>

<Setter TargetName="border" Property="Background" Value="{DynamicResource PrimaryHueLightBrush}" />code>

<Setter TargetName="border" Property="Opacity" Value="0.2" />code>

</Trigger>

</ControlTemplate.Triggers>

</ControlTemplate>

</Setter.Value>

</Setter>

</Style>

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

/// <summary>

/// 系统导航菜单实体类

/// </summary>

public class MenuBar : BindableBase

{

private string icon;

/// <summary>

/// 菜单图标

/// </summary>

public string Icon

{

get { return icon; }

set { icon = value; }

}

private string title;

/// <summary>

/// 菜单名称

/// </summary>

public string Title

{

get { return title; }

set { title = value; }

}

private string nameSpace;

/// <summary>

/// 菜单命名空间

/// </summary>

public string NameSpace

{

get { return nameSpace; }

set { nameSpace = value; }

}

}

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

public static class PrismManager

{

/// <summary>

/// 首页区域

/// </summary>

public static readonly string MainViewRegionName = "MainViewRegion";

/// <summary>

/// 设置页区域

/// </summary>

public static readonly string SettingsViewRegionName = "SettingsViewRegion";

}

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

public class MainViewModel : BindableBase

{

public MainViewModel(IRegionManager regionManager)

{

MenuBars = new ObservableCollection<MenuBar>();

CreateMenuBar();

NavigateCommand = new DelegateCommand<MenuBar>(Navigate);

this.regionManager = regionManager;

}

private void Navigate(MenuBar obj)

{

if (obj == null || string.IsNullOrWhiteSpace(obj.NameSpace))

return;

regionManager.Regions[PrismManager.MainViewRegionName].RequestNavigate(obj.NameSpace, back =>

{

});

}

public DelegateCommand<MenuBar> NavigateCommand { get; private set; }//做导航

private readonly IRegionManager regionManager;

//ObservableCollection是一个动态属性集合,可以动态地添加和删除其中的元素

private ObservableCollection<MenuBar> menuBars;//动态属性集合

public ObservableCollection<MenuBar> MenuBars

{

get { return menuBars; }

set

{

menuBars = value;

RaisePropertyChanged();//通知属性值发生了变化

}

}

void CreateMenuBar()

{

MenuBars.Add(new MenuBar() { Icon = "Home", Title = "首页", NameSpace = "IndexView" });

MenuBars.Add(new MenuBar() { Icon = "NotebookOutline", Title = "待办事项", NameSpace = "ToDoView" });

MenuBars.Add(new MenuBar() { Icon = "NotebookPlus", Title = "备忘录", NameSpace = "MemoView" });

MenuBars.Add(new MenuBar() { Icon = "Cog", Title = "设置", NameSpace = "SettingsView" });

}

}

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

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

public partial class App : PrismApplication

{

protected override Window CreateShell()

{

return Container.Resolve<MainView>();

}

protected override void RegisterTypes(IContainerRegistry containerRegistry)

{

containerRegistry.RegisterForNavigation<ToDoView, ToDoViewModel>();

}

}

3.10主页的全部代码如下

<Window x:Class="ToDoDemo.Views.MainView"code>

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"code>

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"code>

xmlns:d="http://schemas.microsoft.com/expression/blend/2008"code>

xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"code>

xmlns:local="clr-namespace:ToDoDemo.Views"code>

xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"code>

xmlns:i="http://schemas.microsoft.com/xaml/behaviors"code>

xmlns:prism="http://prismlibrary.com/"code>

xmlns:ext="clr-namespace:ToDoDemo.Extensions"code>

mc:Ignorable="d"code>

Height="450" Width="800"code>

WindowStyle="None"code>

AllowsTransparency="True"code>

WindowStartupLocation="CenterScreen">code>

<materialDesign:DialogHost DialogTheme="Inherit" Identifier="RootDialog" code>

SnackbarMessageQueue="{Binding ElementName=MainSnackbar, Path=MessageQueue}">code>

<materialDesign:DrawerHost x:Name="drawerHost" code>

IsLeftDrawerOpen="{Binding ElementName=MenuToggleButton, Path=IsChecked}">code>

<materialDesign:DrawerHost.LeftDrawerContent>

<DockPanel MinWidth="220">code>

<!--侧边栏-->

<ListBox ItemContainerStyle="{StaticResource MyListBoxItemStyle}"code>

ItemsSource="{Binding MenuBars}" x:Name="menuBar">code>

<i:Interaction.Triggers>

<i:EventTrigger EventName="SelectionChanged">code>

<i:InvokeCommandAction Command="{Binding NavigateCommand}"code>

CommandParameter="{Binding ElementName=menuBar,Path=SelectedItem}"/>code>

</i:EventTrigger>

</i:Interaction.Triggers>

<ListBox.ItemTemplate>

<DataTemplate>

<StackPanel Background="Transparent" Orientation="Horizontal">code>

<materialDesign:PackIcon Margin="15,0" Kind="{Binding Icon}"/>code>

<TextBlock Text="{Binding Title}" Margin="10,0"/>code>

</StackPanel>

</DataTemplate>

</ListBox.ItemTemplate>

</ListBox>

</DockPanel>

</materialDesign:DrawerHost.LeftDrawerContent>

<DockPanel>

<materialDesign:ColorZone Padding="16" x:Name="ColorZone"code>

materialDesign:ElevationAssist.Elevation="Dp4"code>

DockPanel.Dock="Top" Mode="PrimaryMid">code>

<DockPanel LastChildFill="True">code>

<!--最小化、最大化、关闭-->

<StackPanel DockPanel.Dock="Right" Orientation="Horizontal">code>

<Button x:Name="btnMin" Content="—" Style="{StaticResource MaterialDesignFlatMidBgButton}" />code>

<Button x:Name="btnMax" Content="☐" Style="{StaticResource MaterialDesignFlatMidBgButton}" />code>

<Button x:Name="btnClose" Content="✕" Style="{StaticResource MaterialDesignFlatMidBgButton}" />code>

</StackPanel>

<!--三横杠-->

<StackPanel Orientation="Horizontal">code>

<ToggleButton x:Name="MenuToggleButton" IsChecked="False"code>

AutomationProperties.Name="HamburgerToggleButton"code>

Style="{StaticResource MaterialDesignHamburgerToggleButton}" />code>

</StackPanel>

</DockPanel>

</materialDesign:ColorZone>

<ContentControl prism:RegionManager.RegionName="{x:Static ext:PrismManager.MainViewRegionName}" />code>

</DockPanel>

</materialDesign:DrawerHost>

</materialDesign:DialogHost>

</Window>

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

public MainView()

{

InitializeComponent();

//点击导航栏后收回

menuBar.SelectionChanged += (s, e) =>

{

drawerHost.IsLeftDrawerOpen = false;

};

//最小化

btnMin.Click += (s, e) => { this.WindowState = WindowState.Minimized; };

//最大化

btnMax.Click += (s, e) =>

{

if (this.WindowState == WindowState.Maximized)

this.WindowState = WindowState.Normal;

else

this.WindowState = WindowState.Maximized;

};

//关闭

btnClose.Click += async (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;

};

}

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



声明

本文内容仅代表作者观点,或转载于其他网站,本站不以此文作为商业用途
如有涉及侵权,请联系本站进行删除
转载本站原创文章,请注明来源及作者。