刚学习时,随便记录的一个小程序。因为有不少人看(应该都是学生),稍作修改,方便阅读。
xaml:样式
<!--绑定事件-->
<Window.CommandBindings> <CommandBinding Command="Open" Executed="OnOpen"/> <CommandBinding Command="Save" Executed="OnSave"/> </Window.CommandBindings> <Grid> <DockPanel> <Menu DockPanel.Dock="Top"> <MenuItem Header="文件"> <MenuItem Header="打开" Command="Open"/> <MenuItem Header="另存为" Command="Save"/> </MenuItem> </Menu> <TextBox x:Name="text1" AcceptsReturn="True" AcceptsTab="True"/> </DockPanel> </Grid>
CS:后台代码
1 public partial class MainWindow : Window 2 { 3 public MainWindow() 4 { 5 InitializeComponent(); 6 } 7 8 private void OnOpen(object sender, ExecutedRoutedEventArgs e) 9 { 10 //学生可能不了解OpenFileDialog类;该类具体介绍参考:https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.openfiledialog?view=netcore-3.1 11 var dlg = new OpenFileDialog() 12 { 13 Title = "简单编辑器-打开", 14 CheckPathExists = true, 15 CheckFileExists = true, 16 Filter = "Text files (*.txt)|*.txt|All files|*.*", 17 InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyComputer) 18 }; 19 if (dlg.ShowDialog() == true) 20 { 21 text1.Text = File.ReadAllText(dlg.FileName); 22 } 23 } 24 25 private void OnSave(object sender, ExecutedRoutedEventArgs e) 26 { 27 var dlg = new SaveFileDialog() 28 { 29 Title = "简单编辑器-另存为", 30 DefaultExt = "txt", 31 Filter = "Text files (*.txt)|*.txt|All files|*.*", 32 }; 33 if (dlg.ShowDialog() == true) 34 { 35 File.WriteAllText(dlg.FileName,text1.Text); 36 } 37 } 38 }
简单读取文件另存文件(仅仅打开txt文件,其他文件没有进行转码)