WPF MaterialDesign 初学项目实战(3)动态侧边栏

这篇具有很好参考价值的文章主要介绍了WPF MaterialDesign 初学项目实战(3)动态侧边栏。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

其他文章

WPF MaterialDesign 初学项目实战(0):github 项目Demo运行
WPF MaterialDesign 初学项目实战(1)首页搭建
WPF MaterialDesign 初学项目实战(2)首页导航栏样式

创建侧边栏实体类

新建MenuBar文件

  • Common
    • Models
      • MenuBar

WPF MaterialDesign 初学项目实战(3)动态侧边栏

添加基本成员

using MaterialDesignColors.Recommended;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.Common.Models
{
    /// <summary>
    /// 系统导航菜单
    /// </summary>
    public class MenuBar : BindableBase//继承BindableBase可以动态修改
    {
        /// <summary>
        /// 菜单图标
        /// </summary>
        public string? Icon { get; set; }

        /// <summary>
        /// 标题
        /// </summary>
        public string? Title { get; set; }   

        /// <summary>
        /// 命名空间
        /// </summary>
        public string? NameSpace { get; set; }

    }
}

创建Views和ViewModels文件夹

注意,Views和VIewModels文件夹的名字是一定要这么写,这和Prism框架的自动绑定有关
绑定关系为:

  • Views
    • xxxView
  • ViewModels
    • xxxViewModel

自动绑定命名空间为:

xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"

WPF MaterialDesign 初学项目实战(3)动态侧边栏
创建MainView和MainViewModel文件
WPF MaterialDesign 初学项目实战(3)动态侧边栏
将MainWindow内容复制到MainView里面,将命名空间进行修改

<Window x:Class="MyToDo.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:MyToDo"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="768"
        Width="1280"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        TextElement.FontWeight="Regular"
        TextElement.FontSize="13"
        TextOptions.TextFormattingMode="Ideal"
        TextOptions.TextRenderingMode="Auto"
        WindowStartupLocation="CenterScreen"
        WindowStyle="None"
        Background="{DynamicResource MaterialDesignPaper}"
        FontFamily="{DynamicResource MaterialDesignFont}">
    <materialDesign:DialogHost DialogTheme="Inherit"
                               Identifier="RootDialog"
                               SnackbarMessageQueue="{Binding ElementName=MainSnackbar, Path=MessageQueue}">

        <materialDesign:DrawerHost IsLeftDrawerOpen="{Binding ElementName=MenuToggleButton, Path=IsChecked}">
            <materialDesign:DrawerHost.LeftDrawerContent>
                <DockPanel MinWidth="220">

                </DockPanel>
            </materialDesign:DrawerHost.LeftDrawerContent>

            <DockPanel>
                <materialDesign:ColorZone Padding="16"
                                          x:Name="MainBody"
                                          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 MovePrevCommand}"
                                    Content="{materialDesign:PackIcon Kind=ArrowLeft,
                                                        Size=24}"
                                    Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}, Path=(TextElement.Foreground)}"
                                    Style="{StaticResource MaterialDesignToolButton}"
                                    ToolTip="Previous Item" />

                            <Button Margin="16,0,0,0"
                                    materialDesign:RippleAssist.Feedback="{Binding RelativeSource={RelativeSource Self}, Path=Foreground, Converter={StaticResource BrushRoundConverter}}"
                                    Command="{Binding MoveNextCommand}"
                                    Content="{materialDesign:PackIcon Kind=ArrowRight,
                                                        Size=24}"
                                    Foreground="{Binding RelativeSource={RelativeSource AncestorType={x:Type FrameworkElement}}, Path=(TextElement.Foreground)}"
                                    Style="{StaticResource MaterialDesignToolButton}"
                                    ToolTip="Next Item" />


                            <TextBlock Margin="25,0,0,0"
                                       HorizontalAlignment="Center"
                                       VerticalAlignment="Center"
                                       AutomationProperties.Name="Material Design In XAML Toolkit"
                                       FontSize="22"
                                       Text="笔记本" />
                        </StackPanel>

                        <StackPanel Orientation="Horizontal"
                                    DockPanel.Dock="Right">
                            <Image Width="25"
                                   Height="25"
                                   Source="/static/img/User/icon.png">
                                <Image.Clip>
                                    <EllipseGeometry Center="12.5,12.5"
                                                     RadiusX="12.5"
                                                     RadiusY="12.5" />
                                </Image.Clip>
                            </Image>
                            <Button x:Name="minBtn"
                                    Content="一"
                                    Style="{StaticResource MaterialDesignFlatMidBgButton}" />
                            <Button x:Name="maxBtn"
                                    Content="口"
                                    Style="{StaticResource MaterialDesignFlatMidBgButton}" />
                            <Button x:Name="closeBtn"
                                    Content="X"
                                    Style="{StaticResource MaterialDesignFlatMidBgButton}" />
                        </StackPanel>



                    </DockPanel>
                </materialDesign:ColorZone>

            </DockPanel>
        </materialDesign:DrawerHost>
    </materialDesign:DialogHost>
</Window>

MainViewModel文件,添加View文件上下文

using MyToDo.Common.Models;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyToDo.ViewModels
{
    public class MainViewModel : BindableBase//继承BindableBase可以动态更新
    {
        public MainViewModel()
        {
            MenuBars = new ObservableCollection<MenuBar>();
            CreateMenuBar();
        }

        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 = "Notebook", Title = "代办事项", NameSpace = "ToDoView" });
            MenuBars.Add(new MenuBar { Icon = "NotebookEdit", Title = "备忘录", NameSpace = "MemoView" });
            MenuBars.Add(new MenuBar { Icon = "CogOutline", Title = "设置", NameSpace = "SettingView" });
        }
    }
}

PS:为什么要有private menuBars 和 public MenuBars
WPF MaterialDesign 初学项目实战(3)动态侧边栏

        public ObservableCollection<MenuBar> MenuBars
        {
            get { return MenuBars; }//这里会报错
            set { MenuBars = value; RaisePropertyChanged(); }
        } //动态更新列表


        private ObservableCollection<MenuBar> menuBars;
        public ObservableCollection<MenuBar> MenuBars
        {
            get { return menuBars; }
            set { menuBars= value; RaisePropertyChanged(); }
        } //动态更新列表

删除原来的MainWindow文件

在App.xmal里面修改启动窗口

 public partial class App : PrismApplication
    {
        /// <summary>
        /// 重写运行主窗口
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        protected override Window CreateShell()
        {
            //重定向主窗口
            - return Container.Resolve<MainWindow>();
            + return Container.Resolve<MainView>();
            
        }

        /// <summary>
        /// 依赖注入
        /// </summary>
        /// <param name="containerRegistry"></param>
        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
           
        }
    }

将元素添加到MainView页面
绑定数据上下文:{Binding 属性名}

注意:Views文件夹和ViewModels文件夹必须这样命名,启用Prism的自动联系上下文功能,并且对应文件名为MainView和MainViewModels

WPF MaterialDesign 初学项目实战(3)动态侧边栏

prism启动上下文功能:

xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
<materialDesign:DrawerHost IsLeftDrawerOpen="{Binding ElementName=MenuToggleButton, Path=IsChecked}">
            <materialDesign:DrawerHost.LeftDrawerContent>
                <DockPanel MinWidth="220">
                    <StackPanel>
                        <Image Width="50"
                               Height="50"
                               Source="/static/img/User/icon.png">
                            <Image.Clip>
                                <EllipseGeometry Center="25,25"
                                                 RadiusX="25"
                                                 RadiusY="25" />
                            </Image.Clip>
                        </Image>
                        <TextBlock  Text="Gclove2000"
                                    HorizontalAlignment="Center"
                                    />

                        <ListBox ItemsSource="{Binding MenuBars}" >
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <materialDesign:PackIcon Kind="{Binding Icon}" />
                                        <TextBlock Text="{Binding Title}" Margin="10,0"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>
                    </StackPanel>
                </DockPanel>
            </materialDesign:DrawerHost.LeftDrawerContent>

运行效果:
WPF MaterialDesign 初学项目实战(3)动态侧边栏

修改MaterialDesign 的默认主题

在App.xmal文件中修改为黑色主题

WPF MaterialDesign 初学项目实战(3)动态侧边栏

<prism:PrismApplication x:Class="MyToDo.App"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:local="clr-namespace:MyToDo"
                        xmlns:prism="http://prismlibrary.com/"
                        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <materialDesign:
                - BundledTheme BaseTheme="Light"
                + 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>

WPF MaterialDesign 初学项目实战(3)动态侧边栏

如何添加自定义样式

在App.xmal文件中添加样式信息

<prism:PrismApplication x:Class="MyToDo.App"
                        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                        xmlns:local="clr-namespace:MyToDo"
                        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>
            <!--自定义样式 样式名:MyListBoxItemStyle,样式挂载:ListBoxItem-->
            <Style x:Key="MyListBoxItemStyle" TargetType="ListBoxItem">
                <!--自定义高度-->
                <Setter Property="MinHeight"
                        Value="40" />
                <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}" />
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</prism:PrismApplication>

在对应元素中引用样式

<ListBox ItemsSource="{Binding MenuBars}" 
+ ItemContainerStyle="{StaticResource MyListBoxItemStyle}" >
                            <ListBox.ItemTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <materialDesign:PackIcon Kind="{Binding Icon}" Margin="15,0" />
                                        <TextBlock Text="{Binding Title}" Margin="10,0"/>
                                    </StackPanel>
                                </DataTemplate>
                            </ListBox.ItemTemplate>
                        </ListBox>

实现效果:有点丑,可以后面改一下
WPF MaterialDesign 初学项目实战(3)动态侧边栏

设置点击范围

WPF MaterialDesign 初学项目实战(3)动态侧边栏

<StackPanel Orientation="Horizontal"
            VerticalAlignment="Center"
            + Background="Transparent">没设置为蓝色点击范围,设置了为红色点击范围
    <materialDesign:PackIcon Kind="{Binding Icon}"
                             Margin="15,0" />
    <TextBlock Text="{Binding Title}"
               Margin="10,0" />
</StackPanel>

设置鼠标悬停效果

也是设置触发器
App.xmal

<!--自定义样式 样式名:MyListBoxItemStyle,样式挂载:ListBoxItem-->
<Style x:Key="MyListBoxItemStyle" TargetType="ListBoxItem">
   <!--自定义高度-->
   <Setter Property="MinHeight"
           Value="40" />
   <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.4" />
                   + </Trigger>
               </ControlTemplate.Triggers>
           </ControlTemplate>
       </Setter.Value>
   </Setter>
</Style>

最终效果:

WPF MaterialDesign 初学项目实战(3)动态侧边栏文章来源地址https://www.toymoban.com/news/detail-449512.html

到了这里,关于WPF MaterialDesign 初学项目实战(3)动态侧边栏的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • wpf复制xaml及其cs窗体到其他项目 添加现有项,选 .xaml.cs,点添加即可。VS2022

    添加现有项,选 LoadingWindow.xaml.cs,点添加即可。

    2024年02月09日
    浏览(28)
  • 【开源免费】Vue+SpringBoot打造图书管理系统,初学者入门实战项目

    作者主页 :Designer 小郑 作者简介 :3年JAVA全栈开发经验,专注JAVA技术、系统定制、远程指导,致力于企业数字化转型,CSDN博客专家,阿里云社区专家博主,蓝桥云课讲师。 文末获取源码,项目编号: S 066 。 color{red}{文末获取源码,项目编号:S066。} 文末获取源码,项目编

    2024年02月10日
    浏览(40)
  • 【开源免费】Vue+SpringBoot打造超市账单管理系统,初学者入门实战项目

    作者主页 :Designer 小郑 作者简介 :3年JAVA全栈开发经验,专注JAVA技术、系统定制、远程指导,致力于企业数字化转型,CSDN博客专家,阿里云社区专家博主,蓝桥云课讲师。 标题 说明 项目名称 超市账单管理系统 color{red}{超市账单管理系统} 超市账单管理系统 源码获取 ht

    2024年02月09日
    浏览(42)
  • 2023初学者如何玩转玩转PyTorch?《21个项目玩转PyTorch实战》

    通过经典项目入门 PyTorch,通过前沿项目提升 PyTorch,基于PyTorch玩转深度学习,本书适合人工智能、机器学习、深度学习方面的人员阅读,也适合其他 IT 方面从业者,另外,还可以作为相关专业的教材。 京东自营购买链接:https://item.jd.com/13522327.html PyTorch 是基于 Torch 库的开

    2024年02月06日
    浏览(39)
  • 【unity项目实战】3DRPG游戏开发07——其他详细的设计

    参考原视频链接: 【视频】:https://space.bilibili.com/370283072 注意 :本文为学习笔记记录,推荐支持原作者,去看原视频自己手敲代码理解更加深入

    2024年02月05日
    浏览(34)
  • WPF实战项目十二(API篇):配置AutoMapper

    1、新建类库WPFProjectShared,在类库下新建文件夹Dtos,新建BaseDto.cs,继承INotifyPropertyChanged,实现通知更新。  2、WPFProjectAPI添加引用WPFProjectShared  3、新建待办事项传输实体TodoDto.cs,继承BaseDto.cs 4、在api层引入AutoMapper,并新建文件夹Extensions,新建帮助类AutoMapperProFile.cs,继承

    2024年02月11日
    浏览(27)
  • WPF实战项目十四(API篇):登录注册接口

    1、新建UserDto.cs 2、新增ILoginService接口 3、实现LoginService接口 4、新增登录控制器LoginController 5、添加AutoMapper映射关系 6、在program.cs里面添加服务 7、F5运行项目

    2024年02月10日
    浏览(29)
  • WPF实战项目十(API篇):引入工作单元UnitOfWork

    1、通过github地址:https://github.com/arch/UnitOfWork,下载UnitOfWork的代码,将工作单元部分的代码引用到自己的项目,新增UnitOfWork文件夹。 2、在UnitOfWork文件夹下引用UnitOfWork下的IPagedList.cs、PagedList.cs类,WPFProjectAPI项目引用WPFProjectShared项目。 3、然后在program.cs下添加UnitOfWork的服务

    2024年02月16日
    浏览(39)
  • WPF+Halcon 培训项目实战(10):HS组件绘制图案

    为了更好地去学习WPF+Halcon,我决定去报个班学一下。原因无非是想换个工作。相关的教学视频来源于下方的Up主的提供的教程。这里只做笔记分享,想要源码或者教学视频可以和他联系一下。 微软系列技术教程 WPF 年度公益课程 Halcon开发 CSDN博客专栏 个人学习的Gitee 项目地址

    2024年02月03日
    浏览(34)
  • WPF实战项目十一(API篇):待办事项功能api接口

    1、新建ToDoController.cs继承基础控制器BaseApiController,但是一般业务代码不写在控制器内,业务代码写在Service,先新建统一返回值格式ApiResponse.cs: 2、新建基础Service接口:IBaseService.cs,包含CRUD方法: 3、新建待办事项接口IToDoService.cs,继承IBaseService 4、新建实现类ToDoService.cs,

    2024年02月13日
    浏览(30)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包