Day03 左侧菜单数据绑定

本文档详细介绍了如何在WPF项目中使用Prism框架进行左侧菜单的数据绑定。首先,遵循Prism的约定创建项目结构,包括Models、Views和ViewModels文件夹。在ViewModels中,利用ObservableCollection初始化菜单数据,并在MainView.xaml中通过AutoWireViewModel实现自动绑定。接着,展示了如何调整左侧菜单的样式,包括在App.xaml中更改主题颜色,定义ListBoxItem的自定义模板,以及使用触发器实现选中效果。最后,提供了当前章节的源码供参考。
摘要由CSDN通过智能技术生成

一.左侧菜单数据绑定

左侧菜单


1.首先,进行项目结构塔建。按照Prism 框架约定,要使用自动查找绑定功能。即View (视图)中自动查找并绑定到对应的ViewModel(视图模型,处理视图业务逻辑)。就需要在项目中按约定,创建的视图后缀必须以 View 结尾和视图模型后缀必须以 ViewModel 结尾。

  • 例如: xxxView.xamlxxx.ViewModel.cs

Model-View-ViewModel

  • Models 文件夹,存放实体类,并且实体类要继承自Prism 框架的 BindableBase,目的是让实体类支持数据的动态变更

例如: 系统导航菜单实体类(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; }
		}

	}

  • Views 文件夹,用于存放视图。例如:首页视图 MainView.xaml
  • ViewModels 文件夹,用于存放对应视图的业务逻辑处理类,例如首页视图模型类 MainViewModel(处理业务逻辑)

View-ViewModel

  1. Prism 框架中,一些视图或类的定义都是有约定的。例如:视图统一使用xxxView 结尾。视图模形统一使用xxxViewModel 结尾。这样做的原因是:第一规范,第二,方便使用 Prism 进行动态的方式绑定上下文的时候,能自动找到对应类。
  2. 如何让 Prism 支持自动绑定上下文(自动查找View绑定到对应ViewModel)。
  • 需要在xxx.xaml视图中引入Prism 命名空间
xmlns:prism="http://prismlibrary.com/"

然后 再通过 prism 名称 设置ViewModelLocator 中的 AutoWireViewModelTrue。这样就完成了自动绑定功能

 prism:ViewModelLocator.AutoWireViewModel="True"

2.在ViewModels文件夹中,创建MainViewModel 逻辑处理类

  • 创建左侧菜单的数据,需要使用到一个动态的属性集合 ObservableCollection 来存放菜单的数据

ObservableCollection

  • 初始化菜单数据
    public class MainViewModel: 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 = "NotebookCheckOutline", Title = "待办事项", NameSpace = "ToDoView" });
            MenuBars.Add(new MenuBar() { Icon = "NotebookPlusOutline", Title = "忘备录", NameSpace = "MemoView" });
            MenuBars.Add(new MenuBar() { Icon = "Cog", Title = "设置", NameSpace = "SettingsView" });
        }
    }
  • NameSpace 主要用于设置导航的视图名称
  • Title 显示的标题
  • Icon 设备 Material DesignThemes UI 框架里面的图标名称

3.MainView.xaml 前端进行菜单绑定数据

  • ListBox列表数据的绑定。需要使用ListBox 的自定义模板,也就是 ListBox.ItemTemplate,并且写法是固定的。
    模板使用示例如下:
<!--列表-->
<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!--在这里添加内容数据-->
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
  • 在MainView.xaml 中使用示例。通过在MainViewModel定义的MenuBars 菜单数据集合,在ListBox中通过 ItemsSource 绑定MenuBars ,进行渲染出数据列表。
<!--列表-->
<ListBox ItemsSource="{Binding MenuBars}">
    <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>

注意,视图 MainView.xaml 中需要添加AutoWireViewModel=“True”,让其动态绑定数据上下文

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

注意:项目中的MainWindow.xaml 已经改成了MainView.xaml,并且把启动页设置成 MainView了
App.xmal

  • 最终项目结构

MyToDo

2.左侧菜单样式调整

  • 在App.xaml 资源文件中,更改默认的主题颜色为黑色

App.xaml

  • 自定义左侧列表选中的样式

需要重写自定义样式
在App.xaml 文件中 资源字典 ResourceDictionary 节点中,设置Style 属性,并且在Style节点里面来进行样式重写

  • Style 使用方式
  1. TargetType :设置作用的目标类型
  2. Setter :设计器,里面有2个常用属性,分别是PropertyValue。用来改变设置作用的目标类型一些属性的值
  3. key: 通过指定的key 来使用重写的样式

示例3:设置ListBoxItem 属性中的最小行高为40

<Style TargetType="ListBoxItem">
    <Setter Property="MinHeight" Value="40"/>
</Style>
  1. Property 中有一个特别的属性:Template。用于改变控件的外观样式。并且也有固定的写法
    示例4:
<Setter Property="Template">
    <Setter.Value>
        <ControlTemplate TargetType="{x:Type ListBoxItem}">

        </ControlTemplate>
    </Setter.Value>
</Setter>

TargetType 有2种写法

  1. 一种是直接用Style 设置一些属性,可以这样写 TargetType=“ListBoxItem”。示例3
  2. 另外一种写法是,当需要使用到自定义模板,也就是要改变控件的外观样式时,Property 设置的值为 Template,里面TargetType 写法就变成这样 TargetType=“{x:Type ListBoxItem}”。示例4
  3. 使用自定义的模板时,需要使用到一个属性 ContentPresenter,把原有模板的属性原封不动的投放到自定义模板。
  4. 触发器,它按条件应用属性值或执行操作。并且使用Template 自定义控件样式后,需要搭配触发器进行使用。

App.xaml 中修改左侧菜单选中自定义模板示例:

<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">
            <!--第一个Border 设置边框样式-->
            <Setter Property="BorderThickness" TargetName="borderHeader" Value="4,0,0,0"/>
            <!--第一个Border 设置边框颜色,value 动态绑定主要是为了适应主题颜色更改时,边框也着变-->
            <Setter Property="BorderBrush" TargetName="borderHeader" Value="{DynamicResource PrimaryHueLightBrush}"/>
            <!--第二个border 设置选中的样式-->
            <Setter Property="Background" TargetName="border" Value="{DynamicResource PrimaryHueLightBrush}"/>
            <!--第二个border 设置选中的透明度-->
            <Setter Property="Opacity" TargetName="border" Value="0.2"/>
        </Trigger>
        <!--鼠标悬停触发器,如果鼠标悬停时-->
        <Trigger Property="IsMouseOver" Value="True">
            <!--第二个border 设置选中的样式-->
            <Setter Property="Background" TargetName="border" Value="{DynamicResource PrimaryHueLightBrush}"/>
            <!--第二个border 设置选中的透明度-->
            <Setter Property="Opacity" TargetName="border" Value="0.2"/>
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>
  1. 样式写完后,如果需要在MainView.xmal 的ListBox中使用这个样式资源文件,是通过指定Key 来使用

资源文件key:MyListBoxItemStyle

二.当前章节完整源码

1.MainView.xaml

<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"
        xmlns:prism="http://prismlibrary.com/"
        prism:ViewModelLocator.AutoWireViewModel="True"
        WindowStyle="None" WindowStartupLocation="CenterScreen" AllowsTransparency="True"
         Style="{StaticResource MaterialDesignWindow}"
        TextElement.Foreground="{DynamicResource MaterialDesignBody}"
        Background="{DynamicResource MaterialDesignPaper}"
        TextElement.FontWeight="Medium"
        TextElement.FontSize="14"
        FontFamily="{materialDesign:MaterialDesignFont}"
        mc:Ignorable="d"
        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
        Title="MainWindow" Height="768" Width="1280">
    <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" >

                    <!--头像-->
                    <StackPanel DockPanel.Dock="Top" Margin="0,20">
                        <Image Source="/Images/user.jpg" Width="50" Height="50">
                            <Image.Clip>
                                <EllipseGeometry Center="25,25" RadiusX="25" RadiusY="25" />
                            </Image.Clip>
                        </Image>
                        <TextBlock Text="WPF gg" Margin="0,10" HorizontalAlignment="Center" />
                    </StackPanel>

                    <!--列表-->
                    <ListBox ItemContainerStyle="{StaticResource MyListBoxItemStyle}" ItemsSource="{Binding MenuBars}">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal" Background="Transparent">
                                    <materialDesign:PackIcon Kind="{Binding Icon}" Margin="15,0" />
                                    <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="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="16,0,0,0"
                             HorizontalAlignment="Center"
                             VerticalAlignment="Center"
                             AutomationProperties.Name="Material Design In XAML Toolkit"
                             FontSize="22"
                             Text="笔记本" />
                        </StackPanel>
                        <!--上右边图标-->
                        <StackPanel DockPanel.Dock="Right" Orientation="Horizontal">
                            <Image Source="/Images/user.jpg" Width="25" Height="25">
                                <Image.Clip>
                                    <EllipseGeometry Center="12.5,12.5" RadiusX="12.5" RadiusY="12.5" />
                                </Image.Clip>
                            </Image>
                            <Button x:Name="btnMin" Style="{StaticResource MaterialDesignFlatMidBgButton}">
                                <materialDesign:PackIcon Kind="MoveResizeVariant" />
                            </Button>
                            <Button x:Name="btnMax" Style="{StaticResource MaterialDesignFlatMidBgButton}">
                                <materialDesign:PackIcon Kind="CardMultipleOutline" />
                            </Button>
                            <Button x:Name="btnClose" Style="{StaticResource MaterialDesignFlatMidBgButton}" Cursor="Hand">
                                <materialDesign:PackIcon Kind="WindowClose" />
                            </Button>
                        </StackPanel>
                    </DockPanel>

                </materialDesign:ColorZone>

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

2.MainViewModel

namespace MyToDo.ViewModels
{
    public class MainViewModel: 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 = "NotebookCheckOutline", Title = "待办事项", NameSpace = "ToDoView" });
            MenuBars.Add(new MenuBar() { Icon = "NotebookPlusOutline", Title = "忘备录", NameSpace = "MemoView" });
            MenuBars.Add(new MenuBar() { Icon = "Cog", Title = "设置", NameSpace = "SettingsView" });
        }
    }
}

3.App.xaml

<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:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:prism="http://prismlibrary.com/">
    <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>
            <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">
                                    <!--第一个Border 设置边框样式-->
                                    <Setter Property="BorderThickness" TargetName="borderHeader" Value="4,0,0,0"/>
                                    <!--第一个Border 设置边框颜色,value 动态绑定主要是为了适应主题颜色更改时,边框也着变-->
                                    <Setter Property="BorderBrush" TargetName="borderHeader" Value="{DynamicResource PrimaryHueLightBrush}"/>
                                    <!--第二个border 设置选中的样式-->
                                    <Setter Property="Background" TargetName="border" Value="{DynamicResource PrimaryHueLightBrush}"/>
                                    <!--第二个border 设置选中的透明度-->
                                    <Setter Property="Opacity" TargetName="border" Value="0.2"/>
                                </Trigger>
                                <!--鼠标悬停触发器,如果鼠标悬停时-->
                                <Trigger Property="IsMouseOver" Value="True">
                                    <!--第二个border 设置选中的样式-->
                                    <Setter Property="Background" TargetName="border" Value="{DynamicResource PrimaryHueLightBrush}"/>
                                    <!--第二个border 设置选中的透明度-->
                                    <Setter Property="Opacity" TargetName="border" Value="0.2"/>
                                </Trigger>
                            </ControlTemplate.Triggers>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ResourceDictionary>
    </Application.Resources>
</prism:PrismApplication>

上一章 设计首页导航条下一章 左侧菜单导航
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小丫头呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值