0


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 添加

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

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

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

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

App.xaml全文如下:

<prism:PrismApplication x:Class="ToDoDemo.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:ToDoDemo"
             xmlns:prism="http://prismlibrary.com/"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <materialDesign:BundledTheme BaseTheme="Dark" PrimaryColor="DeepPurple" SecondaryColor="Lime" />
                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />
            </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"

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

主页面最终引用:

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

<Window x:Class="ToDoDemo.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:ToDoDemo.Views"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:prism="http://prismlibrary.com/"
        xmlns:ext="clr-namespace:ToDoDemo.Extensions"
        mc:Ignorable="d"
        Height="450" Width="800"
        WindowStyle="None"
        AllowsTransparency="True"
        WindowStartupLocation="CenterScreen">
</Window>

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

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

Releases · MaterialDesignInXAML/MaterialDesignInXamlToolkit (github.com)

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

<Style x:Key="MyListBoxItemStyle" TargetType="ListBoxItem">
    <Setter Property="MinHeight" Value="40" />
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                <Grid>
                    <Border x:Name="borderHeader" />
                    <Border x:Name="border" />
                    <ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalAlignment}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                </Grid>

                <ControlTemplate.Triggers>
                    <Trigger Property="IsSelected" Value="True">
                        <Setter TargetName="borderHeader" Property="BorderThickness" Value="4,0,0,0" />
                        <Setter TargetName="borderHeader" Property="BorderBrush" Value="{DynamicResource PrimaryHueLightBrush}" />
                        <Setter TargetName="border" Property="Background" Value="{DynamicResource PrimaryHueLightBrush}" />
                        <Setter TargetName="border" Property="Opacity" Value="0.2" />
                    </Trigger>

                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter TargetName="border" Property="Background" Value="{DynamicResource PrimaryHueLightBrush}" />
                        <Setter TargetName="border" Property="Opacity" Value="0.2" />
                    </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"
        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:ToDoDemo.Views"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        xmlns:i="http://schemas.microsoft.com/xaml/behaviors"
        xmlns:prism="http://prismlibrary.com/"
        xmlns:ext="clr-namespace:ToDoDemo.Extensions"
        mc:Ignorable="d"
        Height="450" Width="800"
        WindowStyle="None"
        AllowsTransparency="True"
        WindowStartupLocation="CenterScreen">
    <materialDesign:DialogHost DialogTheme="Inherit" Identifier="RootDialog" 
                            SnackbarMessageQueue="{Binding ElementName=MainSnackbar, Path=MessageQueue}">
        <materialDesign:DrawerHost x:Name="drawerHost"  
                                IsLeftDrawerOpen="{Binding ElementName=MenuToggleButton, Path=IsChecked}">
            <materialDesign:DrawerHost.LeftDrawerContent>
                <DockPanel MinWidth="220">
                    <!--侧边栏-->
                    <ListBox ItemContainerStyle="{StaticResource MyListBoxItemStyle}"
                          ItemsSource="{Binding MenuBars}" x:Name="menuBar">
                        <i:Interaction.Triggers>
                            <i:EventTrigger EventName="SelectionChanged">
                                <i:InvokeCommandAction Command="{Binding NavigateCommand}"
                                                    CommandParameter="{Binding ElementName=menuBar,Path=SelectedItem}"/>
                            </i:EventTrigger>
                        </i:Interaction.Triggers>

                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Background="Transparent" Orientation="Horizontal">
                                    <materialDesign:PackIcon Margin="15,0" Kind="{Binding Icon}"/>
                                    <TextBlock Text="{Binding Title}" Margin="10,0"/>
                                </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="True">
                        <!--最小化、最大化、关闭-->
                        <StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
                            <Button x:Name="btnMin" Content="—" Style="{StaticResource MaterialDesignFlatMidBgButton}" />
                            <Button x:Name="btnMax" Content="☐" Style="{StaticResource MaterialDesignFlatMidBgButton}" />
                            <Button x:Name="btnClose" Content="✕" Style="{StaticResource MaterialDesignFlatMidBgButton}" />
                        </StackPanel>
                        <!--三横杠-->
                        <StackPanel Orientation="Horizontal">
                            <ToggleButton x:Name="MenuToggleButton" IsChecked="False"
                                       AutomationProperties.Name="HamburgerToggleButton"
                                       Style="{StaticResource MaterialDesignHamburgerToggleButton}" />
                        </StackPanel>
                    </DockPanel>
                </materialDesign:ColorZone>

                <ContentControl prism:RegionManager.RegionName="{x:Static ext:PrismManager.MainViewRegionName}" />
            </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博客

标签: wpf c# 后端

本文转载自: https://blog.csdn.net/Ronion123/article/details/136320107
版权归原作者 Ronion123 所有, 如有侵权,请联系我们删除。

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

还没有评论