C#WPF实战出真汁12--【菜品维护】

1、菜品维护功能

菜品维护模块的功能与餐桌维护的功能一样的,包括有:全选,分页,新增,删除,修改,列表展示

2、UI布局

StackPanel控件,是 XAML(如 WPF、UWP、Xamarin.Forms)中的一种布局控件,用于沿水平或垂直方向依次排列子元素。默认情况下,子元素按垂直方向堆叠,可通过属性调整排列方式。

适用场景

  • 需要简单线性排列的界面(如工具栏、菜单项)。
  • 动态添加或移除子元素时自动调整布局。
  • 不适合复杂嵌套或需要精确控件的场景(此时建议使用 Grid 或 RelativePanel)。

<UserControl
    x:Class="HQ.fResApp.UControls.CaiPinWeiHu"
    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:i="http://schemas.microsoft.com/expression/2010/interactivity"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
    xmlns:vm="clr-namespace:HQ.fResApp.ViewModel"
    Padding="20"
    d:DesignHeight="450"
    d:DesignWidth="1000"
    Background="#f6f9ff"
    mc:Ignorable="d">
    <UserControl.DataContext>
        <vm:CaiPinWeiHuListModel />
    </UserControl.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="80" />
            <RowDefinition Height="20" />
            <RowDefinition />
            <RowDefinition Height="73" />
        </Grid.RowDefinitions>
        <Grid Background="#ffffff">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition Width="430" />
            </Grid.ColumnDefinitions>
            <StackPanel Orientation="Horizontal">
                <TextBox
                    Width="160"
                    Height="40"
                    Margin="20,10,20,0"
                    pu:TextBoxHelper.Watermark="输入搜索关键字"
                    FontSize="15"
                    Foreground="#909399"
                    Text="{Binding DishTableKey}" />
                <ComboBox
                    Width="160"
                    Height="40"
                    Margin="0,10,20,0"
                    Padding="10,0"
                    pu:ComboBoxHelper.Watermark="请选择菜品类型"
                    DisplayMemberPath="mtName"
                    FontSize="15"
                    Foreground="#909399"
                    ItemsSource="{Binding DishTypeList}"
                    SelectedValue="{Binding mtGuid, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    SelectedValuePath="mtGuid">
                    <!--  下拉框选项更改事件,CommandParameter绑定整个下拉框控件  -->
                    <i:Interaction.Triggers>
                        <i:EventTrigger EventName="SelectionChanged">
                            <i:InvokeCommandAction Command="{Binding LoadDishTypeCmd}" CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ComboBox}}" />
                        </i:EventTrigger>
                    </i:Interaction.Triggers>
                </ComboBox>
                <Button
                    x:Name="btnSearch"
                    Width="100"
                    Height="40"
                    Margin="0,10,20,0"
                    Padding="-10,0,0,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.ClickStyle="Sink"
                    pu:ButtonHelper.CornerRadius="20"
                    pu:ButtonHelper.HoverBrush="#009BFF"
                    pu:ButtonHelper.Icon="/HQ.fResApp;component/Resources/icon/search.png"
                    pu:IconHelper.Width="40"
                    Background="#FF009BFF"
                    BorderBrush="#FF009BFF"
                    Command="{Binding FindCommand}"
                    Content="查询"
                    Cursor="Hand"
                    FontSize="16"
                    Foreground="#ffffff"
                    IsDefault="true" />
                <Button
                    Width="100"
                    Height="40"
                    Margin="0,10,20,0"
                    Padding="-10,0,0,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.ClickStyle="Sink"
                    pu:ButtonHelper.CornerRadius="20"
                    pu:ButtonHelper.HoverBrush="#009BFF"
                    pu:ButtonHelper.Icon="/HQ.fResApp;component/Resources/icon/Refresh.png"
                    pu:IconHelper.Width="40"
                    Background="LightSlateGray"
                    BorderBrush="#FF009BFF"
                    Command="{Binding ResetCommand}"
                    CommandParameter="dining"
                    Content="重置"
                    Cursor="Hand"
                    FontSize="16"
                    Foreground="#ffffff" />
            </StackPanel>
            <StackPanel
                Grid.Column="1"
                HorizontalAlignment="Right"
                Orientation="Horizontal">
                <Button
                    x:Name="btnAdd"
                    Width="100"
                    Height="40"
                    Margin="0,15,20,0"
                    Padding="-10,0,0,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.ClickStyle="Sink"
                    pu:ButtonHelper.CornerRadius="20"
                    pu:ButtonHelper.HoverBrush="#65d17f"
                    pu:ButtonHelper.Icon="/HQ.fResApp;component/Resources/icon/add.png"
                    pu:IconHelper.Width="35"
                    Background="#65d17f"
                    BorderBrush="#65d17f"
                    Command="{Binding AddCommand}"
                    Content="新增"
                    Cursor="Hand"
                    FontSize="16"
                    Foreground="#ffffff" />
                <Button
                    Width="100"
                    Height="40"
                    Margin="20,12,20,0"
                    Padding="-10,0,0,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.ClickStyle="Sink"
                    pu:ButtonHelper.CornerRadius="20"
                    pu:ButtonHelper.HoverBrush="#65d17f"
                    pu:ButtonHelper.Icon="/HQ.fResApp;component/Resources/icon/openorder.png"
                    pu:IconHelper.Width="35"
                    Background="Black"
                    BorderBrush="Black"
                    Command="{Binding EditCommand}"
                    CommandParameter="dish"
                    Content="编辑"
                    Cursor="Hand"
                    FontSize="16"
                    Foreground="#ffffff" />
                <Button
                    x:Name="btnDel"
                    Width="100"
                    Height="40"
                    Margin="10,15,20,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.ClickStyle="Sink"
                    pu:ButtonHelper.CornerRadius="20"
                    pu:ButtonHelper.HoverBrush="#FF5722"
                    pu:ButtonHelper.Icon="/HQ.fResApp;component/Resources/icon/remove1.png"
                    pu:IconHelper.Width="35"
                    Background="#FF5722"
                    Command="{Binding DeleteCommand}"
                    BorderBrush="#FF5722"
                    Content="删除"
                    Cursor="Hand"
                    FontSize="16"
                    Foreground="#ffffff" />
            </StackPanel>
        </Grid>
        <Border Grid.Row="1" />
        <DataGrid
            x:Name="dataList"
            Grid.Row="2"
            pu:DataGridHelper.ColumnHorizontalContentAlignment="Center"
            pu:DataGridHelper.HeaderBackground="#FF009BFF"
            pu:DataGridHelper.HeaderForeground="#ffffff"
            pu:DataGridHelper.HeaderMinHeight="50"
            pu:DataGridHelper.HoverBackground="#FF009BFF"
            pu:DataGridHelper.ResizeThumbThickness="0.5"
            pu:DataGridHelper.SelectedBackground="Transparent"
            pu:DataGridHelper.SelectedForeground="Red"
            AlternatingRowBackground="#f7faff"
            AutoGenerateColumns="False"
            CanUserAddRows="False"
            CanUserDeleteRows="False"
            CanUserReorderColumns="False"
            CanUserResizeRows="False"
            FontSize="16"
            ItemsSource="{Binding DishTableList}"
            SelectionMode="Extended"
            SelectionUnit="FullRow">
            <!--  行样式  -->
            <DataGrid.RowStyle>
                <Style TargetType="DataGridRow">
                    <!--  Event绑定MouseLeftButtonUp表示鼠标点击事件,Handler表示具体的事件处理程序  -->
                    <EventSetter Event="MouseLeftButtonUp" Handler="Item_GotFocus" />
                    <Setter Property="Height" Value="40" />
                    <!--  样式触发器,IsMouseOver表示鼠标滑过时事件  -->
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background">
                                <Setter.Value>
                                    <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                                        <GradientStop Offset="0.98" Color="#FF73BCE8" />
                                        <GradientStop Offset="0" Color="White" />
                                    </LinearGradientBrush>
                                </Setter.Value>
                            </Setter>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </DataGrid.RowStyle>
            <DataGrid.Columns>
                <!--  模板列  -->
                <DataGridTemplateColumn>
                    <!--  模板列的头模板  -->
                    <DataGridTemplateColumn.HeaderTemplate>
                        <DataTemplate>
                            <CheckBox
                                VerticalAlignment="Center"
                                pu:CheckBoxHelper.CheckBoxStyle="Switch"
                                Command="{Binding DataContext.DishTableCheckAllCmd, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
                                Content="全选"
                                Foreground="#ffffff"
                                IsChecked="{Binding DataContext.IsCheckAllDishTable, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" />
                        </DataTemplate>
                    </DataGridTemplateColumn.HeaderTemplate>
                    <!--  模板列的单元格模板  -->
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <CheckBox
                                HorizontalAlignment="Center"
                                VerticalAlignment="Center"
                                Command="{Binding DataContext.CheckedDishTable, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}"
                                CommandParameter="{Binding RelativeSource={RelativeSource Mode=Self}, Path=DataContext}"
                                IsChecked="{Binding IsCheck, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                            <!--  此处Binding IsCheck的IsCheck是指InfoCheckVModelBase类中的IsCheck  -->
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <!--  文本列,此处单元格绑定的属性是视图模型中数据源DishTableList中每个数据的DishTableCheckInfo对象的各个属性  -->
                <DataGridTextColumn
                    Width="3*"
                    Binding="{Binding DishTableInfo.msName}"
                    Header="菜品名称"
                    IsReadOnly="True" />
                <DataGridTextColumn
                    Width="2*"
                    Binding="{Binding mtName}"
                    Header="菜品类型"
                    IsReadOnly="True" />
                <DataGridTemplateColumn Width="1*" Header="图片">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image 
                                Source="{Binding DishTableInfo.proImg}"
                                Stretch="UniformToFill">
                                <Image.Style>
                                    <Style TargetType="{x:Type Image}">
                                        <Setter Property="Width" Value="50" />
                                        <Setter Property="Height" Value="50" />
                                        <Style.Triggers>
                                            <Trigger Property="IsMouseOver" Value="True">
                                                <Setter Property="Width" Value="150" />
                                                <Setter Property="Height" Value="150" />
                                            </Trigger>
                                        </Style.Triggers>
                                    </Style> 
                                </Image.Style>
                            </Image>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
                <DataGridTextColumn
                    Width="2*"
                    Binding="{Binding DishTableInfo.msPrice}"
                    Header="单价"
                    IsReadOnly="True" />
                <DataGridTextColumn
                    Width="2*"
                    Binding="{Binding DishTableInfo.msScalar}"
                    Header="库存量"
                    IsReadOnly="True" />
                <DataGridTextColumn
                    Width="2*"
                    Binding="{Binding DishTableInfo.msCost}"
                    Header="成本价"
                    IsReadOnly="True" />
                <DataGridTextColumn
                    Width="2*"
                    Binding="{Binding DishTableInfo.msUnit}"
                    Header="单位"
                    IsReadOnly="True" />
                <DataGridTextColumn
                    Width="3*"
                    Binding="{Binding DishTableInfo.createDate, StringFormat='{}{0:yyyy年MM月dd日 dddd}', ConverterCulture=zh-CN}"
                    Header="创建时间"
                    IsReadOnly="True" />
                <DataGridTextColumn
                    Width="3*"
                    Binding="{Binding DishTableInfo.lastUpDate, StringFormat='{}{0:yyyy年MM月dd日 dddd}', ConverterCulture=zh-CN}"
                    Header="修改时间"
                    IsReadOnly="True" />
            </DataGrid.Columns>
        </DataGrid>
        <Grid Grid.Row="3">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition Width="250" />
            </Grid.ColumnDefinitions>
            <pu:Pagination
                x:Name="tabPagination"
                Height="45"
                Margin="0,0,20,0"
                HorizontalAlignment="Left"
                Background="#963F3F3F"
                CurrentIndex="{Binding DishTableCurrentIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                CurrentIndexChanged="tabPageActiveChanged"
                Cursor="Hand"
                HoverBrush="#FF009BFF"
                Spacing="15"
                TotalIndex="{Binding DishTableTotalIndex, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
            <StackPanel
                Grid.Column="1"
                HorizontalAlignment="Right"
                Orientation="Horizontal">
                <Button
                    Width="20"
                    Height="45"
                    Padding="-35,0,0,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.HoverBrush="Transparent"
                    pu:IconHelper.Width="35"
                    Background="Transparent"
                    BorderBrush="Transparent"
                    Content="共"
                    FontSize="17"
                    FontWeight="ExtraBold"
                    Foreground="#2F4056" />
                <Button
                    x:Name="txtTotalNum"
                    Height="45"
                    Padding="-35,0,0,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.HoverBrush="Transparent"
                    pu:IconHelper.Width="35"
                    Background="Transparent"
                    BorderBrush="Transparent"
                    Content="{Binding DishTableTotalNum, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                    FontSize="17"
                    FontWeight="ExtraBold"
                    Foreground="#FF009BFF" />
                <Button
                    Width="100"
                    Height="45"
                    Padding="-35,0,0,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.HoverBrush="Transparent"
                    pu:IconHelper.Width="35"
                    Background="Transparent"
                    BorderBrush="Transparent"
                    Content="条数据/每页"
                    FontSize="17"
                    FontWeight="ExtraBold"
                    Foreground="#2F4056" />
                <TextBox
                    x:Name="txtPageSize"
                    Grid.Row="2"
                    Width="50"
                    Height="30"
                    HorizontalAlignment="Center"
                    pu:TextBoxHelper.CornerRadius="0"
                    Text="{Binding DishTablePageSize, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                <Button
                    Width="20"
                    Height="45"
                    Padding="-35,0,0,0"
                    pu:ButtonHelper.ButtonStyle="Standard"
                    pu:ButtonHelper.HoverBrush="Transparent"
                    pu:IconHelper.Width="35"
                    Background="Transparent"
                    BorderBrush="Transparent"
                    Content="条"
                    FontSize="17"
                    FontWeight="ExtraBold"
                    Foreground="#2F4056" />
            </StackPanel>
        </Grid>
    </Grid>
</UserControl>

3、视图模型

using HQ.BLL;
using HQ.COMM;
using HQ.fResApp.BaseModel;
using HQ.fResApp.Utils;
using HQ.fResApp.ViewModel.PageViewModel;
using HQ.fResApp.XWindows;
using HQ.MODEL.DBModel;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media.Imaging;
using System.Xml.Linq;

namespace HQ.fResApp.ViewModel
{
    /// <summary>
    /// 菜品视图模型
    /// </summary>
    public class CaiPinWeiHuListModel : ViewModelBase
    {
        DishTableBLL dishTableBLL = new DishTableBLL();//菜品列表
        DishTypeBLL  dishTypeBLL=new DishTypeBLL(); //菜品类型
        BillConsumeBLL billconsumeBLL = new BillConsumeBLL();//消费帐单
        DiningTableBLL diningTableBLL = new DiningTableBLL();//餐桌业务

        public CaiPinWeiHuListModel()
        { 
            DishTypeList = getdishTypeList();//类型列表
            DishTableList = getdishTablePage(); //数据列表
        }


        #region 属性 

        private ObservableCollection<DishTableCheckInfo> dishTableList;
        /// <summary>
        ///菜品列表
        /// </summary>
        public ObservableCollection<DishTableCheckInfo> DishTableList
        {
            get { return dishTableList; }
            set
            {
                dishTableList = value;
                OnPropertyChanged();
            }
        }

        private ObservableCollection<DishType> dishTypeList;
        /// <summary>
        /// 菜品类型,用于绑定下拉框 
        /// </summary>
        public ObservableCollection<DishType> DishTypeList
        {
            get { return dishTypeList; }
            set
            {
                dishTypeList = value;
                OnPropertyChanged();
            }
        }

        private string dishTableKey = "";
        /// <summary>
        /// 菜品搜索时的关键字,默认为空
        /// </summary>
        public string DishTableKey
        {
            get { return dishTableKey; }
            set
            {
                dishTableKey = value;
                OnPropertyChanged();
            }
        }

        private int dishTableCurrentIndex = 1;
        /// <summary>
        /// 当前页,默认第1页
        /// </summary>
        public int DishTableCurrentIndex
        {
            get { return dishTableCurrentIndex; }
            set
            {
                dishTableCurrentIndex = value;
                OnPropertyChanged();
            }
        }

        private int dishTableTotalIndex;
        /// <summary>
        /// 总页数
        /// </summary>
        public int DishTableTotalIndex
        {
            get { return dishTableTotalIndex; }
            set
            {
                dishTableTotalIndex = value;
                OnPropertyChanged();
            }
        }
        private int dishTableTotalNum;
        /// <summary>
        /// 总条数
        /// </summary>
        public int DishTableTotalNum
        {
            get { return dishTableTotalNum; }
            set
            {
                dishTableTotalNum = value;
                OnPropertyChanged();
            }
        }
        private int dishTablePageSize = 10;
        /// <summary>
        /// 每页条数,默认10条
        /// </summary>
        public int DishTablePageSize
        {
            get { return dishTablePageSize; }
            set
            {
                dishTablePageSize = value;
                OnPropertyChanged();
                //当改变每页条数时,触发以下事件
                dishTableList = getdishTablePage(); //菜品数据集合
            }
        } 

        private bool isCheckAllDishTable = false;
        /// <summary>
        /// 菜品全选状态
        /// </summary>
        public bool IsCheckAllDishTable
        {
            get { return isCheckAllDishTable; }
            set
            {
                isCheckAllDishTable = value;
                OnPropertyChanged();
            }
        }

        private string dishTypeGuid = "";
        /// <summary>
        /// 菜品类型编号(主键)
        /// </summary>
        public string DishTypeGuid
        {
            get { return dishTypeGuid; }
            set
            {
                dishTypeGuid = value;
                OnPropertyChanged();
            }
        }


        #endregion

        #region 方法

        /// <summary>
        /// 获取菜品列表分页
        /// </summary>
        /// <returns></returns>
        public ObservableCollection<DishTableCheckInfo> getdishTablePage()
        {
            ObservableCollection<DishTableCheckInfo> TableDataList = new ObservableCollection<DishTableCheckInfo>();
            var parms = new PageParm { page = DishTableCurrentIndex, limit = DishTablePageSize, key = DishTableKey.Trim(), dishtypeId = DishTypeGuid.Trim() };
            var pageRes = dishTableBLL.GetDishTablePages(parms).Result;//分页查询结果
            if (pageRes.statusCode == (int)ApiEnum.Status)
            {
                var _pageResData = pageRes.data;
                var tabList = _pageResData.Items;
                //数据集需要重新处理,将每个数据项加上复选框,用于页面数据展示
                if (tabList != null && tabList.Count != 0)
                {
                    foreach (var item in tabList)
                    {
                        var curTable = new DishTableCheckInfo();
                        curTable.DishTableInfo.pmGuid = item.pmGuid;//主键
                        curTable.DishTableInfo.dtId = item.dtId;//分类id
                        curTable.DishTableInfo.msName = item.msName;//名称
                        curTable.DishTableInfo.msSpell = item.msSpell;//拼写
                        curTable.DishTableInfo.msUnit = item.msUnit;//规格
                        curTable.DishTableInfo.msPrice = item.msPrice;//单价
                        curTable.DishTableInfo.msScalar = item.msScalar;//库存
                        curTable.DishTableInfo.proImg = item.proImg;//图片
                        curTable.mtName = DishTypeList.ToList().Find(x => x.mtGuid == item.dtId).mtName;//菜品类型名称
                        curTable.DishTableInfo.createDate = item.createDate;//创建时间
                        curTable.DishTableInfo.lastUpDate = item.lastUpDate;//更新时间
                        curTable.DishTableInfo.msCost = item.msCost;//成本 
                        curTable.IsCheck = false;//是否选中,默认没有
                        TableDataList.Add(curTable);
                    }
                    DishTableTotalNum = (int)_pageResData.TotalItems;
                    DishTableCurrentIndex = (int)_pageResData.CurrentPage;
                    DishTableTotalIndex = (int)_pageResData.TotalPages;
                }
                else
                {
                    Notice.Show("没有获取到菜品列表数据!", "提示", 3, MessageBoxIcon.Info);
                    Logger.Default.ProcessError((int)ApiEnum.Error, "没有获取到菜品列表数据");
                }
            }
            else
            {
                Notice.Show("没有获取到菜品列表数据!", "提示", 3, MessageBoxIcon.Info);
                Logger.Default.ProcessError(pageRes.statusCode, "获取到菜品列表数据异常");
            }
            return TableDataList;
        }

        /// <summary>
        /// 获取菜品类型列表
        /// </summary>
        /// <returns></returns>
        public ObservableCollection<DishType> getdishTypeList()
        {
            ObservableCollection<DishType> TableDataList = new ObservableCollection<DishType>();
            var _parm = new ParmString { parm = "" };
            var _tabRest = dishTypeBLL.QueryDishTypeList(_parm).Result;
            if (_tabRest.statusCode == (int)ApiEnum.Status)
            {
                var diningTypes = _tabRest.data;
                if (diningTypes != null)
                {
                    foreach (var type in diningTypes)
                    {
                        TableDataList.Add(type);
                    }
                    //添加一个选项
                    TableDataList.Insert(0, new DishType()
                    {
                        mtGuid = "",
                        mtName = "全部"
                    });
                }
            } 
            return TableDataList;
        }


        /// <summary>
        /// 刷新菜品数据
        /// </summary>
        private void RefreshDishTable(object sender, EventArgs e)
        {
            DishTableCurrentIndex = 1;
            DishTablePageSize = 10;
            DishTableKey = "";
            DishTableList = getdishTablePage();
        }

        /// <summary>
        /// PointMenu实体转换DishTable实体
        /// </summary>
        /// <param name="PointMenu">PointMenu实体</param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        private DishTable CreateDishTableModel(PointMenu item)
        {
            DishTable pm = new DishTable();
            pm.pmGuid = item.pmGuid;
            pm.dtId = item.dtId;
            pm.msName = item.msName;
            pm.msSpell = item.msSpell;
            pm.msPrice = item.msPrice;
            pm.msScalar = item.msScalar;
            pm.msCost = item.msCost;
            pm.msUnit = item.msUnit;
            pm.msMoney = item.msMoney;
            pm.stId = item.stId;
            pm.createDate = item.createDate;
            pm.lastUpDate = item.lastUpDate;
            pm.proImg = item.proImg;
            return pm;
        }

        /// <summary>
        /// 根据路径创建图片
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        private BitmapImage CreateImage(string path)
        {
            var myimage = new BitmapImage();
            myimage.BeginInit();
            myimage.UriSource = new Uri(path);
            myimage.EndInit();
            return myimage;
        }

        #endregion

        #region 命令

        /// <summary>
        /// 菜品列表行点击命令
        /// </summary>
        public ICommand CheckedDiningTable
        {
            get
            {
                return new RelayCommand(o =>
                {
                    if (o != null)
                    {
                        var item = o as DishTableCheckInfo;
                        item.IsCheck = !item.IsCheck;
                    }
                });
            }
        }

        /// <summary>
        /// 菜品全选命令
        /// </summary>
        public ICommand DishTableCheckAllCmd
        {
            get
            {
                return new RelayCommand(o =>
                {
                    foreach (var record in this.DishTableList)
                    {
                        record.IsCheck = this.IsCheckAllDishTable;
                    }
                });
            }
        }


        /// <summary>
        /// 菜品类型下拉框选择命令
        /// </summary>
        public ICommand LoadDishTypeCmd
        {
            get
            {
                return new RelayCommand(o =>
                {
                    if (o is ComboBox)
                    {
                        var comboBox = o as ComboBox;
                        if (comboBox.SelectedValue == null)
                        {
                            return;
                        }
                        string selectItemGuid = comboBox.SelectedValue.ToString();//获取下拉框所选项的值,即菜品类型guid
                        DishTypeGuid = selectItemGuid;
                        DishTablePageSize = 10;//恢复每页10条数据
                        DishTableCurrentIndex = 1;//恢复第1页显示
                        DishTableList = getdishTablePage(); //更新菜品数据集合  
                    }
                });
            }
        }


        /// <summary>
        /// 查询命令
        /// </summary>
        public ICommand FindCommand
        {
            get
            {
                return new RelayCommand(o =>
                {
                    DishTableList = getdishTablePage();
                });
            }
        }

        /// <summary>
        /// 重置命令
        /// </summary>
        public ICommand ResetCommand
        {
            get
            {
                return new RelayCommand(o =>
                {
                    DishTableCurrentIndex = 1;//当前页为第1页
                    DishTablePageSize = 10;//每页10条
                    DishTableKey = "";//关键字清空
                    DishTypeGuid = "";//类型清空
                    DishTypeList = getdishTypeList();//类型集合
                    DishTableList = getdishTablePage();//数据集合
                });
            }
        }

        /// <summary>
        /// 新增命令
        /// </summary>
        public ICommand AddCommand
        {
            get
            {
                return new RelayCommand(o =>
                {
                    WindowX AddTable = new DishTableInfo("");
                    if (AddTable != null)
                    {
                        AddTable.Closed += new EventHandler(RefreshDishTable);//注册关闭事件
                        AddTable.ShowDialog();
                    }
                });
            }
        }

        /// <summary>
        /// 编辑命令
        /// </summary>
        public ICommand EditCommand
        {
            get
            {
                return new RelayCommand(o =>
                {
                    List<DishTableCheckInfo> selectList = new List<DishTableCheckInfo>();
                    foreach (var record in this.DishTableList)
                    {
                        if (record.IsCheck)
                        {
                            selectList.Add(record);
                        }
                    }

                    if (selectList.Count == 0)
                    {
                        MessageBoxX.Show("请选择要编辑的数据.", "提示", Application.Current.MainWindow, MessageBoxButton.OK, new MessageBoxXConfigurations()
                        {
                            MessageBoxIcon = MessageBoxIcon.Warning,
                            ButtonBrush = "#F1C825".ToColor().ToBrush(),
                        });
                        return;
                    }
                    if (selectList.Count >= 2)
                    {
                        var _msgRes = MessageBoxX.Show("对不起,一次只能编辑一条数据", "提示", Application.Current.MainWindow, MessageBoxButton.OK, new MessageBoxXConfigurations()
                        {
                            MessageBoxIcon = MessageBoxIcon.Info,
                            ButtonBrush = "#F1C825".ToColor().ToBrush(),
                        });
                        return;
                    }
                    else
                    { 
                        //执行编辑操作
                        string selectid = selectList.Select(r => r.DishTableInfo.pmGuid).ToList().First(); //获取所选菜品主键id
                        WindowX EditWin = new DishTableInfo(selectid);//创建窗体对象
                        if (EditWin != null)
                        {
                            DishTableInfoVModel objvmodel = new DishTableInfoVModel();
                            PointMenu result = dishTableBLL.GetModelByCond(x => x.pmGuid == selectid).Result.data; //根据所选记录的主键获取一条菜品数据 
                            objvmodel.DishTableItem = CreateDishTableModel(result);
                            var filestr = objvmodel.DishTableItem.proImg.Split('/');
                            var filename = filestr[4];
                            //图片文件路径
                            var rootImagPath = Directory.GetCurrentDirectory().Replace(@"\bin\Debug", "") + @"\Resources\proImg\" + filename  ;  
                            //创建图片文件
                            objvmodel.CurrentImgSourcePath = CreateImage(rootImagPath);
                            objvmodel.ShowCurrentImgPro = Visibility.Visible;//显示图片
                            objvmodel.ProImgName = filename;
                            objvmodel.DishType = objvmodel.DishTypeList.FirstOrDefault(x => x.mtGuid == result.dtId); 
                            objvmodel.AddButtonPro = Visibility.Collapsed;//隐藏添加按钮
                            objvmodel.EditButtonPro = Visibility.Visible;//显示编辑按钮
                            EditWin.DataContext = objvmodel;
                            EditWin.Closed += new EventHandler(RefreshDishTable);//注册关闭事件
                            EditWin.ShowDialog();
                        }
                    }
                });
            }
        }

        /// <summary>
        /// 删除命令
        /// </summary>
        public ICommand DeleteCommand
        {
            get
            {
                return new RelayCommand(o =>
                {
                    List<DishTableCheckInfo> selectList = new List<DishTableCheckInfo>();
                    foreach (var record in this.DishTableList)
                    {
                        if (record.IsCheck)
                        {
                            selectList.Add(record);
                        }
                    }
                    if (selectList.Count == 0)
                    {
                        MessageBoxX.Show("请选择要删除的数据.", "提示", Application.Current.MainWindow, MessageBoxButton.OK, new MessageBoxXConfigurations()
                        {
                            MessageBoxIcon = MessageBoxIcon.Warning,
                            ButtonBrush = "#F1C825".ToColor().ToBrush(),
                        });
                        return;
                    }
                    if (selectList.Count > 0)
                    {
                        //删除前判断菜品是否有订单号 
                        List<string> dishOrders = selectList.Select(x => x.DishTableInfo.pmGuid).ToList();
                        foreach (var guidStr in dishOrders)
                        {
                            if (!string.IsNullOrEmpty(guidStr))
                            {
                                //1、先查该菜品的消费帐单
                               List<BillConsume> billlist= billconsumeBLL.GetListByCond(x=>x.msId== guidStr).Result.data; 
                                if (billlist.Count != 0)
                                {
                                    DishTable dt = DishTableList.ToList().Find(x=>x.DishTableInfo.pmGuid==guidStr).DishTableInfo;
                                    foreach(BillConsume bill in billlist)
                                    {
                                        //2、再查消费帐单的餐桌是否在占用
                                        DiningTable table = diningTableBLL.GetModelByCond(x => x.obId == bill.obId).Result.data;
                                        if (table!=null && table.rtState == "占用")
                                        {
                                            MessageBoxX.Show("【"+dt.msName+ "】菜品已被"+table.rName + "点单消费,不能删除", "提示", Application.Current.MainWindow, MessageBoxButton.OK, new MessageBoxXConfigurations()
                                            {
                                                MessageBoxIcon = MessageBoxIcon.Warning,
                                                ButtonBrush = "#F1C825".ToColor().ToBrush(),
                                            });
                                            return;
                                        } 
                                    } 
                                } 
                            }
                        }

                        //删除前提示
                        var _msgRes = MessageBoxX.Show("确定要删除吗?", "提示", Application.Current.MainWindow, MessageBoxButton.YesNo, new MessageBoxXConfigurations()
                        {
                            MessageBoxIcon = MessageBoxIcon.Warning,
                            ButtonBrush = "#F1C825".ToColor().ToBrush(),
                        });
                        if (_msgRes == MessageBoxResult.No)
                        {
                            return;
                        }

                        //开始执行删除操作
                        List<string> dishtbids = selectList.Select(r => r.DishTableInfo.pmGuid).ToList();//获取菜品主键列表
                        var res2 = new ApiResult<string>() { statusCode = (int)ApiEnum.Error };
                        foreach (string pmGuid in dishtbids)
                        {
                            res2 = dishTableBLL.DeleteById(pmGuid).Result;
                        }

                        if (res2.statusCode == (int)ApiEnum.Status)
                        {
                            Notice.Show("成功删除【" + dishtbids.Count + "】条数据", "提示", 3, MessageBoxIcon.Success);
                        }
                        else
                        {
                            Notice.Show("删除失败!", "提示", 3, MessageBoxIcon.Error);
                            Logger.Default.ProcessError(res2.statusCode, "删除餐桌类型失败");
                        }
                        //删除后更新数据
                        RefreshDishTable(null, null);
                    }
                });
            }
        }



        #endregion

    }
}

4、运行效果

原创不易,打字截图不易,走过路过,不要错过,欢迎点赞,收藏,转载,复制,抄袭,留言,动动你的金手指,早日实现财务自由!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hqwest

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

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

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

打赏作者

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

抵扣说明:

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

余额充值