一、实验目的
- 掌握文件类的使用;
- 掌握文件流的操作;
- 掌握二进制数据、文本数据的读写;
- 继续应用WPF技术进行界面编程。
二、实验内容
- 写一个记事本程序:
(1)设计界面,向窗体添加下拉式菜单、多格式文本框(RichTextBox)。
(2)依次为“文件”下的“新建”、“打开”、“保存”菜单项的Click事件添加事件处理函数。可以使用路由命令。
(3)添加“格式”工具栏,可以设置所有文字的粗体、斜体、大小、颜色等样式。
(4)实现文本文件的打开、编辑和保存功能;
提示
1、窗口可用DockPanel进行布局,让菜单和工具栏都位于顶部,即:
DockPanel.Dock="Top"
2、文本文件的编辑可以使用TextBox控件。
3、使用命令绑定,让菜单项和工具栏同时与一个操作相关联。
在MainWindow.xaml的Window标签下加:
<Window.CommandBindings> <CommandBinding Command="ApplicationCommands.New" Executed="NewCommand_Executed"/> <CommandBinding Command="ApplicationCommands.Open" Executed="OpenCommand_Executed"/> <CommandBinding Command="ApplicationCommands.Save" Executed="SaveCommand_Executed"/> </Window.CommandBindings>
在菜单项添加:
<MenuItem Header="新建(_N)" Command="New"/>
在工具栏添加:
<Button Content="新建" Command="New"/>
就可绑定命令。同时Ctrl+O等键盘组合也默认与Open命令相绑定。
其中NewCommand_Executed需要作为一个事件响应方法来实现。
4、添加bool类型_saved字段,标记当前内容是否已保存。(文本格式不属于文件内容,修改格式不会导致_saved字段的改变)
5、打开文件时,弹出打开文件对话框,操作代码如下:
OpenFileDialog dlg = new OpenFileDialog(); dlg.DefaultExt = "*.txt"; dlg.Filter = "Text Files (*.txt)|*.txt"; bool? result = dlg.ShowDialog(); if (result == true) { string fileName = dlg.FileName; }
自此可对该文件名进行操作。
6、保存文件时,实际可实现“另存为”功能。弹出保存文件对话框,操作代码如下:
SaveFileDialog saveFileDialog = new SaveFileDialog(); saveFileDialog.Filter = "文本文件|*.txt|所有文件|*.*"; saveFileDialog.FilterIndex = 0; bool? result = saveFileDialog.ShowDialog(); if (result == true) { string strFile = saveFileDialog.FileName; }
自此可对该文件名进行操作。
7、可以根据自己的想法,添加更加丰富的功能。
源代码
XAML
<Window x:Class="Homework11.MainWindow"
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:Homework11"
mc:Ignorable="d"
Title="记事本" Height="450" Width="800">
<Window.CommandBindings>
<CommandBinding Command="ApplicationCommands.New" Executed="NewCommand_Executed"/>
<CommandBinding Command="ApplicationCommands.Open" Executed="OpenCommand_Executed"/>
<CommandBinding Command="ApplicationCommands.Save" Executed="SaveCommand_Executed"/>
<CommandBinding Command="ApplicationCommands.Print" Executed="PrintCommand_Executed"/>
</Window.CommandBindings>
<DockPanel>
<DockPanel.Resources>
<Style TargetType="{x:Type Button}" x:Key="formatTextStyle">
<Setter Property="FontFamily" Value="Palatino Linotype"></Setter>
<Setter Property="Width" Value="30"></Setter>
<Setter Property="FontSize" Value ="14"></Setter>
<Setter Property="CommandTarget" Value="{Binding ElementName=MainTextBox}"></Setter>
</Style>
<Style TargetType="{x:Type Button}" x:Key="formatImageStyle">
<Setter Property="Width" Value="30"></Setter>
<Setter Property="CommandTarget" Value="{Binding ElementName=MainTextBox}"></Setter>
</Style>
</DockPanel.Resources>
<Menu x:Name="MainMenu" DockPanel.Dock="Top">
<MenuItem Header="文件">
<MenuItem Header="新建(_N)" Command="New"/>
<MenuItem Header="打开(_O)" Command="Open"/>
<MenuItem Header="保存(_S)" Command="Save"/>
<MenuItem Header="打印(_P)" Command="Print"/>
</MenuItem>
<MenuItem Header="格式">
<MenuItem Header="自动换行(_W)"/>
<MenuItem Header="字体(_F)"/>
</MenuItem>
</Menu>
<ToolBar x:Name="MainToolBar" DockPanel.Dock="Top">
<Button Style="{StaticResource formatImageStyle}" Command="New" >
<Image Source="Images/New.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="Open">
<Image Source="Images/Open.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="Save">
<Image Source="Images/Save.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="Print">
<Image Source="Images/Print.png"></Image>
</Button>
</ToolBar>
<!-- This tool bar contains all the editing buttons. -->
<ToolBar Name="mainToolBar" Height="30" DockPanel.Dock="Top">
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Cut" ToolTip="Cut">
<Image Source="Images/EditCut.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Copy" ToolTip="Copy">
<Image Source="Images/EditCopy.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Paste" ToolTip="Paste">
<Image Source="Images/EditPaste.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Undo" ToolTip="Undo">
<Image Source="Images/EditUndo.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="ApplicationCommands.Redo" ToolTip="Redo">
<Image Source="Images/EditRedo.png"></Image>
</Button>
<Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleBold" ToolTip="Bold">
<Image Source="Images/EditBold.png"></Image>
</Button>
<Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleItalic" ToolTip="Italic">
<Image Source="Images/EditItalic.png"></Image>
</Button>
<Button Style="{StaticResource formatTextStyle}" Command="EditingCommands.ToggleUnderline" ToolTip="Underline">
<Image Source="Images/EditUnderline.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.IncreaseFontSize" ToolTip="Grow Font">
<Image Source="Images\CharacterGrowFont.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.DecreaseFontSize" ToolTip="Shrink Font">
<Image Source="Images\CharacterShrinkFont.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.ToggleBullets" ToolTip="Bullets">
<Image Source="Images\ListBullets.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.ToggleNumbering" ToolTip="Numbering">
<Image Source="Images/ListNumbering.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignLeft" ToolTip="Align Left">
<Image Source="Images\ParagraphLeftJustify.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignCenter" ToolTip="Align Center">
<Image Source="Images\ParagraphCenterJustify.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignRight" ToolTip="Align Right">
<Image Source="Images\ParagraphRightJustify.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.AlignJustify" ToolTip="Align Justify">
<Image Source="Images\ParagraphFullJustify.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.IncreaseIndentation" ToolTip="Increase Indent">
<Image Source="Images\ParagraphIncreaseIndentation.png"></Image>
</Button>
<Button Style="{StaticResource formatImageStyle}" Command="EditingCommands.DecreaseIndentation" ToolTip="Decrease Indent">
<Image Source="Images\ParagraphDecreaseIndentation.png"></Image>
</Button>
</ToolBar>
<RichTextBox x:Name="MainTextBox" DockPanel.Dock="Top" Height="300" TextChanged="MainTextBox_TextChanged" AcceptsTab="True">
<FlowDocument>
<Paragraph>
<Run></Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
<StatusBar DockPanel.Dock="Bottom">
<TextBlock x:Name="MainStatusBar"></TextBlock>
</StatusBar>
</DockPanel>
</Window>
CS
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
namespace Homework11
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private bool _saved;
private string title {
set { Title = value; }
get { return Title; }
}
public MainWindow()
{
InitializeComponent();
}
private void NewCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
_saved = false;
TextRange range;
range = new TextRange(MainTextBox.Document.ContentStart, MainTextBox.Document.ContentEnd);
range.Text = "";
}
private void OpenCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.DefaultExt = "*.txt";
dlg.Filter = "Text Files (*.txt)|*.txt";
bool? result = dlg.ShowDialog();
string str=null;
if (result == true)
{
string _fileName = dlg.FileName;
TextRange range;
FileStream fStream;
if (File.Exists(_fileName))
{
title = _fileName;
range = new TextRange(MainTextBox.Document.ContentStart, MainTextBox.Document.ContentEnd);
fStream = new FileStream(_fileName, FileMode.OpenOrCreate);
range.Load(fStream, DataFormats.XamlPackage);
fStream.Close();
}
}
}
private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (_saved) {
return;
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "文本文件|*.txt|所有文件|*.*";
saveFileDialog.FilterIndex = 0;
bool? result = saveFileDialog.ShowDialog();
if (result == true)
{
string strFile = saveFileDialog.FileName;
TextRange range;
FileStream fStream;
range = new TextRange(MainTextBox.Document.ContentStart, MainTextBox.Document.ContentEnd);
fStream = new FileStream(strFile, FileMode.Create);
range.Save(fStream, DataFormats.XamlPackage);
fStream.Close();
_saved = true;
MainStatusBar.Text = "保存到" + strFile;
}
}
private void PrintCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
PrintDialog pd = new PrintDialog();
if ((pd.ShowDialog() == true))
{
//use either one of the below
pd.PrintVisual(MainTextBox as Visual, "printing as visual");
pd.PrintDocument((((IDocumentPaginatorSource)MainTextBox.Document).DocumentPaginator), "printing as paginator");
}
}
private void MainTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
_saved = false;
}
private void LineCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
}
private void FontSelectCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
}
}
}
运行结果
三、实验心得与体会
- 掌握文件类的使用;
- 掌握文件流的操作;
- 掌握二进制数据、文本数据的读写;
- 继续应用WPF技术进行界面编程;
- 掌握RichTextBox控件的使用;
- 掌握对话框的使用。
参考文章
https://blog.csdn.net/u011389706/article/details/55805476
https://blog.csdn.net/weixin_43272781/article/details/106284772