C#實戰(zhàn)之備忘錄的制作詳解
1.概述
前幾天群里有人問如何制作備忘錄,感覺這樣一個小實例挺適合新手們?nèi)腴T學(xué)習使用,所以就抽空做了出來。界面如下圖

這個備忘錄主要包括了如下功能:
① 備忘錄信息的增、刪、改、查;
② 備忘錄時間到了以后進行語音播報。
功能很簡單,但是要實現(xiàn)這么一個功能,也涉及眾多的知識點,接下來詳細進行分解。
2.內(nèi)容詳述
①界面button的圖標
圖標圖片可以上網(wǎng)上下載,下載好以后放到項目目錄中,然后在項目中找到你的圖片——>右鍵包括在項目中——>再右鍵,點擊屬性:
復(fù)制到輸出目錄,更改為始終復(fù)制。
生成操作,更改為內(nèi)容。

前臺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>② 數(shù)據(jù)源:這里我采用從xml讀取并綁定到界面,界面如果有修改,在頁面退出時進行數(shù)據(jù)保存,當然你也可以使用數(shù)據(jù)庫去操作
XML文件位置:根目錄的RawData下

XML文件數(shù)據(jù)內(nèi)容如下:

MemorandumModel數(shù)據(jù)模型定義:
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是我們所有數(shù)據(jù)的集合,為了方便界面查詢,界面綁定了MemorandumShowList 這個集合
xml讀?。?/p>
public void XmlDocReader()
{
//XmlDocument讀取xml文件
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(XmlDocPath);
//獲取xml根節(jié)點
XmlNode xmlRoot = xmlDoc.DocumentElement;
if (xmlRoot == null)
return;
//讀取所有的節(jié)點
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()
{
//獲取根節(jié)點對象
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);
}④查詢:如果全選選中,則顯示全部內(nèi)容,未勾選,則采用link去匹配選中信息去篩選,我這里是所有信息去匹配的,你也可以自己修改下,去只匹配某一項或幾項內(nèi)容
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() );
}⑤標題欄未輸入內(nèi)容時顯示灰色提示字體,有輸入時輸入內(nèi)容顯示黑色字體:
這里采用事件處理:獲取到光標時
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);
}⑦行號獲?。涸谛羞x擇改變事件中去做
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線程執(zhí)行
/// <summary>
/// 微軟語音識別
/// </summary>
/// <param name="content">提示內(nèi)容</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,默認情況下,時間只顯示年月日,如果需要顯示時分,需要設(shè)定: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這個控件,她綁定的是一個字符串類型的數(shù)據(jù),所以添加時候,需要將他轉(zhuǎn)換為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枚舉內(nèi)容綁定:
public ObservableCollection<EvenType> EvenTypeList { get; set; } = new ObservableCollection<EvenType>();foreach (EvenType evenType in Enum.GetValues(typeof(EvenType)))
{
EvenTypeList.Add(evenType);
}⑩④關(guān)于gridcontrol TableView 的常用屬性介紹
TableView?的常用屬性: ? AllowPerPixelScrolling //逐像素滾動; AllowScrollAnimation //滾動動畫,當下拉滾動條時有動畫效果 NavigationStyle //選中方式是一行還是單元格 ShowIndicator //是否在每一行之前顯示小方塊 UseEvenRowBackground //隔行其背景顏色會有所區(qū)分 AllowScrollToFocusedRow //允許滾動到選中行 AllowResizing //允許調(diào)整尺寸 AllowSorting //允許排序 AutoWidth //允許自動調(diào)整列寬 AllowMoveColumnToDropArea //允許將一列拖到空白處進行分組 AllowGrouping //允許分組 AllowFilterEditor //允許顯示過濾盤 AllowEditing //允許編輯 ShowGroupPanel//顯示分組panel ShowHorizontalLines ShowVerticalLines //顯示表格中每行每列垂直和水平線 IsColumnMenuEnabled //是否關(guān)閉右鍵列菜單
3.前臺代碼
直接上代碼,比較簡單,不展開講解了:
<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="狀態(tài)" 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>
?
4.效果演示

以上就是C#實戰(zhàn)之備忘錄的制作詳解的詳細內(nèi)容,更多關(guān)于C#備忘錄的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
c# 從內(nèi)存中釋放Selenium chromedriver.exe
這篇文章主要介紹了c# 從內(nèi)存中釋放Selenium chromedriver.exe的方法,幫助大家更好的理解和使用c#,感興趣的朋友可以了解下2021-01-01
C#數(shù)據(jù)結(jié)構(gòu)之隊列(Quene)實例詳解
這篇文章主要介紹了C#數(shù)據(jù)結(jié)構(gòu)之隊列(Quene),結(jié)合實例形式較為詳細的講述了隊列的功能、原理與C#實現(xiàn)隊列的相關(guān)技巧,需要的朋友可以參考下2015-11-11
Entity?Framework使用ObjectContext類
這篇文章介紹了Entity?Framework使用ObjectContext類的方法,文中通過示例代碼介紹的非常詳細。對大家的學(xué)習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06

