[C# 项目实战]: 制作一个备忘录(经典)

01

概述

     前几天群里有人问如何制作备忘录,感觉这样一个小实例挺适合新手们入门学习使用,所以就抽空做了出来。界面如下图:

5dcbe902b7cee91d06ccce35b87ab14c.png

这个备忘录主要包括了如下功能:

① 备忘录信息的增、删、改、查;

② 备忘录时间到了以后进行语音播报。

功能很简单,但是要实现这么一个功能,也涉及众多的知识点,接下来详细进行分解。

软谋的.NET全套架构视频,大多视频包含源码,录制时间(初中级是2019~2020高级架构是2020~2021),原价6499,现仅需299元。这个活动周三推出后,受到热捧,仅一个技术群就几十人抢购!最后几天活动,目录和介绍:点击下方超链接查看

太牛了!三天时间几百人加我咨询这份.NET架构视频

需要的加微zls20210502,进技术群的加微mm1552923,备注进群

02


内容详述

①界面button的图标:

a44597101c09ce94f6d7faf6be7230df.png

图标图片可以上网上下载,下载好以后放到项目目录中,然后在项目中找到你的图片——>右键包括在项目中——>再右键,点击属性:

复制到输出目录,更改为始终复制。

生成操作,更改为内容。

e7ef8773a1ef2e59b230f63c090212b3.png

前台XMAL操作:

<Button Margin="15,5" MinWidth="60" cal:Message.Attach="[Event Click] = [Action SearchClick]" >
                <WrapPanel >
                    <Image Source="/Images/search.png" Width="15" Height="15" />
                    <TextBlock Text="查找" VerticalAlignment="Center" />
                </WrapPanel>
            </Button>

② 数据源:这里我采用从xml读取并绑定到界面,界面如果有修改,在页面退出时进行数据保存,当然你也可以使用数据库去操作

XML文件位置:根目录的RawData下

57904880bf9d4724db4c05a3bd054b58.png

XML文件数据内容如下:

c83586cd52706b2954c0720d9b595eec.png

MemorandumModel数据模型定义:

public class MemorandumModel 
    {
        public string Title { get; set; }
        public EvenType EvenType { get; set; }
        public DateTime DateTime { get; set; }
        public bool IsComplete { get; set; }
    }

③XML文件的读取和保存:MemorandumRealList是我们所有数据的集合,为了方便界面查询,界面绑定了MemorandumShowList 这个集合

xml读取:

public void XmlDocReader()
        {
            //XmlDocument读取xml文件
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(XmlDocPath);
            //获取xml根节点
            XmlNode xmlRoot = xmlDoc.DocumentElement;
            if (xmlRoot == null)
                return;
         
            //读取所有的节点
            foreach (XmlNode node in xmlRoot.SelectNodes("MemorandumModel"))
            {
                MemorandumRealList.Add(new MemorandumModel()
                {
                    Title = node.SelectSingleNode("Title").InnerText,
                    EvenType = (EvenType)Enum.Parse(typeof(EvenType), node.SelectSingleNode("EvenType").InnerText),
                    DateTime = Convert.ToDateTime(node.SelectSingleNode("DateTime").InnerText),
                    IsComplete = Convert.ToBoolean(node.SelectSingleNode("IsComplete").InnerText)
                }); 
            }
            MemorandumShowList = new  ObservableCollection<MemorandumModel>(MemorandumRealList);
        }

xml文件保存:

public void SaveXmlDoc()
        {
            //获取根节点对象
            XDocument document = new XDocument();
            XElement xmlRoot = new XElement("MemorandumModels");


            XElement memorandumModel;
            foreach (var memorandumReal in MemorandumRealList)
            {
                memorandumModel = new XElement($"MemorandumModel");
                memorandumModel.SetElementValue("Title", memorandumReal.Title);
                memorandumModel.SetElementValue("EvenType", memorandumReal.EvenType);
                memorandumModel.SetElementValue("DateTime", memorandumReal.DateTime);
                memorandumModel.SetElementValue("IsComplete", memorandumReal.IsComplete);
                xmlRoot.Add(memorandumModel);
            }
            xmlRoot.Save(XmlDocPath);
        }

④查询:如果全选选中,则显示全部内容,未勾选,则采用link去匹配选中信息去筛选,我这里是所有信息去匹配的,你也可以自己修改下,去只匹配某一项或几项内容

public void SearchClick()
        {
            SaveXmlDoc();
            if (SelectAll)
            {
                MemorandumShowList = new ObservableCollection<MemorandumModel>(MemorandumRealList);
                return;
            }
            MemorandumShowList = new ObservableCollection<MemorandumModel>(
                MemorandumRealList.Where(
                    t => t.EvenType == EvenTypeList[SelectedIndex]
                    ).Where(s => s.IsComplete == IsCompleteStatus
                    ).Where(p => p.Title == TitleText
                     ).Where(x => x.DateTime == DateTime.Parse(DataTimeContext)
                    ) .ToList() );
        }

⑤标题栏未输入内容时显示灰色提示字体,有输入时输入内容显示黑色字体:

这里采用事件处理:获取到光标时

public void LostFocus()
        {
            if (string.IsNullOrEmpty(TitleText))
            {
                TitleText = "备忘录标题";
                TitleColor = Color.DimGray;
            }
        }

光标离开时:

public void GotFocus()
        {
            TitleText = "";
            TitleColor = Color.Black;
        }

⑥选中行删除:

public void DeleteClick()
        {
            MemorandumRealList.Remove(SelectedItem);
            MemorandumShowList.Remove(SelectedItem);
        }

⑦行号获取:在行选择改变事件中去做

public void GridControl_SelectedItemChanged(object sender, SelectedItemChangedEventArgs e)
        {
            GridControl gd = sender as GridControl;
            SelectRow = gd.GetSelectedRowHandles()[0];//选中行的行号
        }

⑧添加信息:

public void Add()
        {
            MemorandumRealList.Add(new MemorandumModel()
            {
                Title = titleText,
                DateTime =DateTime.Parse(DataTimeContext),
                EvenType = EvenTypeList[SelectedIndex],
                IsComplete = IsCompleteStatus
            });
            MemorandumShowList.Add(new MemorandumModel()
            {
                Title = titleText,
                DateTime = DateTime.Parse(DataTimeContext),
                EvenType = EvenTypeList[SelectedIndex],
                IsComplete = IsCompleteStatus
            });
        }

⑨修改信息:

public void Modify()
        {
            MemorandumRealList[SelectRow] = new MemorandumModel()
            {
                Title = titleText,
                DateTime = DateTime.Parse(DataTimeContext),
                EvenType = EvenTypeList[SelectedIndex],
                IsComplete = IsCompleteStatus
            };
            MemorandumShowList[SelectRow] = new MemorandumModel()
            {
                Title = titleText,
                DateTime = DateTime.Parse(DataTimeContext),
                EvenType = EvenTypeList[SelectedIndex],
                IsComplete = IsCompleteStatus
            };
        }

⑩定时器查询:采用using System.Threading.Tasks;下的单线程定时器DispatcherTimer,

定义和初始化:

private DispatcherTimer timer;
 
             timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromMinutes(1);
            timer.Tick += timer1_Tick;
            timer.Start();

定时器事件:我这里每隔一分钟查询一次,查询到当前事件到了提醒时间就进行一次语音播报:

private void timer1_Tick(object sender, EventArgs e)
        {
            foreach (var memorandum in MemorandumRealList)
            {
                if(DateTime.Now >= memorandum.DateTime)
                {
                    SpeakAsync(memorandum.Title);
                }
            }
        }

⑩①:语音播报:这里开了task线程执行

/// <summary>
        /// 微软语音识别
        /// </summary>
        /// <param name="content">提示内容</param>
        public static void SpeakAsync(string content)
        {
            try
            {
                Task.Run(() =>
                {
                    SpVoice voice = new SpVoice();
                    voice.Rate = 1;//速率[-10,10]
                    voice.Volume = 10;//音量[0,100]
                    voice.Voice = voice.GetVoices().Item(0);//语音库
                    voice.Speak(content);
                });


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

⑩② 界面时间处理:

  • 界面的表格采用的dev控件gridcontrol,默认情况下,时间只显示年月日,如果需要显示时分,需要设定:EditSettings如下

<dxg:GridColumn  Header="提醒时间" FieldName="DateTime" MinWidth="120" >
                    <dxg:GridColumn.EditSettings>
                        <!--<xctk:DateEditSettings DisplayFormat="dd-MM-yyyy HH:mm:ss.fff"/>-->
                        <xctk:DateEditSettings DisplayFormat="yyyy-MM-dd HH:mm"/>
                    </dxg:GridColumn.EditSettings>
                </dxg:GridColumn>

如果使用的是wpf 自带的表格控件datagrid,相对好处理

<DataGridTextColumn Header="提醒时间" Binding="{Binding Path=DateTime,StringFormat='yyyy年MM月dd日 HH:mm:ss'}" MinWidth="300" />
  • 界面顶端的时间控件采用:toolkit下的xctk1:DateTimeUpDown这个控件

    她绑定的是一个字符串类型的数据,所以添加时候,需要将他转换为datetime类型, DateTime.Parse(DataTimeContext),或者

     DateTime = Convert.ToDateTime(DataTimeContext)

    <xctk1:DateTimeUpDown x:Name="_minimum"  Format="Custom" FormatString="yyyy/MM/dd HH:mm" 
                                      Text="{Binding DataTimeContext}" 
                                       HorizontalAlignment="Left" VerticalAlignment="Center"
                                      Value="2016/01/01T12:00"  Margin="15,5"/>

⑩③combobox枚举内容绑定:

public ObservableCollection<EvenType> EvenTypeList { get; set; } = new ObservableCollection<EvenType>();
foreach (EvenType evenType in Enum.GetValues(typeof(EvenType)))
            {
                EvenTypeList.Add(evenType);
            }

⑩④关于gridcontrol TableView 的常用属性介绍

TableView 的常用属性:


AllowPerPixelScrolling //逐像素滚动;
AllowScrollAnimation //滚动动画,当下拉滚动条时有动画效果
NavigationStyle //选中方式是一行还是单元格
ShowIndicator //是否在每一行之前显示小方块
UseEvenRowBackground //隔行其背景颜色会有所区分
AllowScrollToFocusedRow //允许滚动到选中行
AllowResizing //允许调整尺寸
AllowSorting //允许排序
AutoWidth //允许自动调整列宽
AllowMoveColumnToDropArea //允许将一列拖到空白处进行分组
AllowGrouping //允许分组
AllowFilterEditor //允许显示过滤盘
AllowEditing //允许编辑
ShowGroupPanel//显示分组panel
ShowHorizontalLines   ShowVerticalLines //显示表格中每行每列垂直和水平线
IsColumnMenuEnabled //是否关闭右键列菜单

03


前台代码

直接上代码,比较简单,不展开讲解了:

<UserControl
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Caliburn.Micro.Hello"
              xmlns:cal="http://www.caliburnproject.org" 
              xmlns:sys="clr-namespace:System;assembly=mscorlib"
             xmlns:dxg="http://schemas.devexpress.com/winfx/2008/xaml/grid" xmlns:xctk="http://schemas.devexpress.com/winfx/2008/xaml/editors" xmlns:xctk1="http://schemas.xceed.com/wpf/xaml/toolkit" x:Class="Caliburn.Micro.Hello.MemorandumView" 
             mc:Ignorable="d" 
             d:DesignHeight="450" d:DesignWidth="800" >
    <UserControl.Resources>
        <local:FontColorConverter x:Key="FontColorConverter" />
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="HorizontalContentAlignment" Value="Left"/>
            <Setter Property="VerticalContentAlignment" Value="Center"/>
            <Setter Property="Width" Value="100"/>
</Style>
        <Style TargetType="{x:Type CheckBox}">
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="Foreground" Value="Black"/>
</Style>
        <Style TargetType="Button">
            <Setter Property="Foreground" Value="Black"/>
</Style>
        <DataTemplate x:Key="rowIndicatorContentTemplate">
            <StackPanel VerticalAlignment="Stretch"
                        HorizontalAlignment="Stretch">
                <TextBlock Text="{Binding RowHandle.Value}"
                           TextAlignment="Center" 
                           Foreground="Black"/>
            </StackPanel>
        </DataTemplate>
    </UserControl.Resources>
    <StackPanel Orientation="Vertical">
        <StackPanel Orientation="Horizontal">
            <TextBox Text="{Binding TitleText}"  Margin="15,5" 
                     cal:Message.Attach="[Event GotFocus] = [Action GotFocus];[Event LostFocus] = [Action LostFocus]" 
                     Foreground="{Binding TitleColor, Converter={StaticResource FontColorConverter}}"/>
            <ComboBox ItemsSource="{Binding EvenTypeList}" Margin="15,5"  SelectedIndex="{Binding SelectedIndex}" MinWidth="100" Foreground="Black"/>
            <!--<DatePicker Text="{Binding DataTimeContext,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
                        SelectedDate="{x:Static sys:DateTime.Now}" 
                        HorizontalAlignment="Left" VerticalAlignment="Center" Margin="15,5"  />-->
            <xctk1:DateTimeUpDown x:Name="_minimum"  Format="Custom" FormatString="yyyy/MM/dd HH:mm" 
                                  Text="{Binding DataTimeContext}" 
                                   HorizontalAlignment="Left" VerticalAlignment="Center"
                                  Value="2016/01/01T12:00"  Margin="15,5"/>


            <CheckBox IsChecked="{Binding IsCompleteStatus}" Margin="15,5" Content="是否完成" Foreground="Black"/>
            <Button Margin="15,5" MinWidth="60" cal:Message.Attach="[Event Click] = [Action SearchClick]" >
                <WrapPanel >
                    <Image Source="/Images/search.png" Width="15" Height="15" />
                    <TextBlock Text="查找" VerticalAlignment="Center" />
                </WrapPanel>
            </Button>
        </StackPanel>
        <Border BorderBrush="LightBlue" CornerRadius="2" BorderThickness="2" >
        <dxg:GridControl AutoGenerateColumns="AddNew" EnableSmartColumnsGeneration="True"  AllowLiveDataShaping="True" 
                         cal:Message.Attach="[Event SelectedItemChanged] = [Action GridControl_SelectedItemChanged($source,$event)];" 
                         ItemsSource="{Binding MemorandumShowList}" SelectedItem="{Binding SelectedItem}" 
                         Height="330" Foreground="Black">
            <dxg:GridControl.View>
                <dxg:TableView ShowTotalSummary="True" AllowMoveColumnToDropArea="False" 
                               AllowGrouping="False" AutoExpandOnDrag="False" 
                               ShowDragDropHint="False" ShowGroupPanel="False" 
                               AllowColumnMoving="False" AllowResizing="False" Foreground="Black"
                               RowIndicatorContentTemplate="{StaticResource rowIndicatorContentTemplate}" />
            </dxg:GridControl.View>
                <dxg:GridColumn  Header="标题" FieldName="Title"   MinWidth="100"/>
                <dxg:GridColumn  Header="类型" FieldName="EvenType"  MinWidth="100"/>
                <dxg:GridColumn  Header="提醒时间" FieldName="DateTime" MinWidth="120" >
                    <dxg:GridColumn.EditSettings>
                        <!--<xctk:DateEditSettings DisplayFormat="dd-MM-yyyy HH:mm:ss.fff"/>-->
                        <xctk:DateEditSettings DisplayFormat="yyyy-MM-dd HH:mm"/>
                    </dxg:GridColumn.EditSettings>
                </dxg:GridColumn>
                <dxg:GridColumn  Header="状态" FieldName="IsComplete"  MinWidth="100"/>
        </dxg:GridControl>
        </Border>
        <StackPanel Orientation="Horizontal">
            <CheckBox IsChecked="{Binding SelectAll}" Margin="35,5" Content="全选"/>
            <Button Margin="35,5" MinWidth="60" cal:Message.Attach="[Event Click] = [Action DeleteClick]" >
                <WrapPanel >
                    <Image Source="/Images/delete.png" Width="15" Height="15" />
                    <TextBlock Text="删除" VerticalAlignment="Center" />
                </WrapPanel>
            </Button>
            <Button Margin="35,5" MinWidth="60" Name="Add">
                <WrapPanel >
                    <Image Source="/Images/add.png" Width="15" Height="15" />
                    <TextBlock Text="添加" VerticalAlignment="Center" />
                </WrapPanel>
            </Button>
            <Button Margin="35,5" MinWidth="60" Name="Modify">
                <WrapPanel >
                    <Image Source="/Images/modify.png" Width="15" Height="15"/>
                    <TextBlock Text="修改" VerticalAlignment="Center" />
                </WrapPanel>
            </Button>
        </StackPanel>
    </StackPanel>
</UserControl>

04


效果演示

e9c1e88d5c9fb8f7abfc5e0e9ea0bf81.gif

05


源码

源码下载 

链接:https://pan.baidu.com/s/1yExT_zXFfd6TiAJYoD8kIw 

提取码:关注下面这个公众号后对话框发送【备忘录】,会自动回复提取码

或者直接添加小编微信:mm1552923   获取。

技术群:添加小编微信并备注进群

小编微信:mm1552923   

公众号:dotNet编程大全      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值