-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathErrorDetailPage.xaml.cs
More file actions
964 lines (863 loc) · 37.9 KB
/
ErrorDetailPage.xaml.cs
File metadata and controls
964 lines (863 loc) · 37.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media.Imaging;
using Microsoft.UI.Xaml.Navigation;
using System;
using Windows.Storage.Pickers;
using Windows.Storage;
using ElectronicCorrectionNotebook.Services;
using System.Threading.Tasks;
using Windows.System;
using System.IO;
using System.Threading;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage.Streams;
using System.Collections.Generic;
using Windows.Media.Core;
using System.Diagnostics;
using ElectronicCorrectionNotebook.DataStructure;
using Microsoft.UI.Xaml.Media;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Microsoft.UI;
using System.Collections.ObjectModel;
using CommunityToolkit.WinUI.Controls;
using System.Linq;
using System.Collections.Specialized;
namespace ElectronicCorrectionNotebook
{
public sealed partial class ErrorDetailPage : Page, INotifyPropertyChanged
{
#region Binding Properties
private MainWindow _mainWindow;
public MainWindow MainWindowInstance
{
get => _mainWindow;
set
{
if (_mainWindow != value)
{
_mainWindow = value;
OnPropertyChanged();
}
}
}
private ErrorItem errorItem;
public ErrorItem ErrorItem
{
get => errorItem;
set
{
errorItem = value;
OnPropertyChanged();
}
}
private ObservableCollection<TagItem> filteredSuggestedTags;
public ObservableCollection<TagItem> FilteredSuggestedTags
{
get => filteredSuggestedTags;
set
{
filteredSuggestedTags = value;
OnPropertyChanged();
}
}
private Brush _selectedFontColor = new SolidColorBrush(Colors.Black);
public Brush SelectedFontColor
{
get => _selectedFontColor;
set
{
_selectedFontColor = value;
OnPropertyChanged();
}
}
private Brush _selectedHLColor = new SolidColorBrush(Colors.Transparent);
public Brush SelectedHLColor
{
get => _selectedHLColor;
set
{
_selectedHLColor = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
private readonly string appDataPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ElectronicCorrectionNotebook");
private CancellationTokenSource cts;
private Microsoft.UI.Xaml.Controls.Image dialogImage;
private TextBlock dialogTextBlock;
private MediaPlayerElement dialogMediaPlayer;
// 初始化页面
public ErrorDetailPage()
{
this.InitializeComponent();
cts = new CancellationTokenSource();
this.MainWindowInstance = (MainWindow)App.MainWindow;
this.DataContext = this;
FilteredSuggestedTags = new ObservableCollection<TagItem>(MainWindowInstance.SuggestedTagList);
}
private void TagItems_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TagItem newItem in e.NewItems)
{
if (!MainWindowInstance.SuggestedTagList
.Any(tag => string.Equals(tag.Name, newItem.Name, StringComparison.Ordinal)))
{
MainWindowInstance.SuggestedTagList.Add(newItem);
}
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (TagItem oldItem in e.OldItems)
{
var tagToRemove = MainWindowInstance.SuggestedTagList
.FirstOrDefault(tag => string.Equals(tag.Name, oldItem.Name, StringComparison.Ordinal));
if (tagToRemove != null)
{
MainWindowInstance.SuggestedTagList.Remove(tagToRemove);
}
}
}
else if (e.Action == NotifyCollectionChangedAction.Reset)
{
MainWindowInstance.SuggestedTagList.Clear();
}
// 临时解决方案
/*if (e.Action == NotifyCollectionChangedAction.Remove)
{
MainWindowInstance.UpdateSuggestedTagList();
}*/
}
// 导航到页面 Binding自动绑定数据到UI控件
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
ErrorItem = e.Parameter as ErrorItem;
if (ErrorItem != null)
{
if (ErrorItem.TagItems == null)
{
ErrorItem.TagItems = new ObservableCollection<TagItem>();
}
// 在这里订阅 TagItems 的 CollectionChanged 事件
ErrorItem.TagItems.CollectionChanged += TagItems_CollectionChanged;
// 获取软件数据文件夹路径
StorageFolder localFolder = await StorageFolder.GetFolderFromPathAsync(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ElectronicCorrectionNotebook"));
StorageFolder rtfFolder = await localFolder.CreateFolderAsync("rtfFiles", CreationCollisionOption.OpenIfExists);
string rtfFileName = $"{ErrorItem.Id}.rtf";
StorageFile rtfFile = await rtfFolder.CreateFileAsync(rtfFileName, CreationCollisionOption.OpenIfExists);
// 加载富文本框的内容
try
{
// 检查文件是否存在
StorageFile file = await rtfFolder.GetFileAsync(rtfFileName);
if (file != null)
{
// 如果是已经存在的页面
using (var stream = await file.OpenAsync(FileAccessMode.Read))
{
DescriptionRichEditBox.Document.LoadFromStream(Microsoft.UI.Text.TextSetOptions.FormatRtf, stream);
}
}
else
{
// 文件不存在,初始化一个空的 RTF 文档
DescriptionRichEditBox.Document.SetText(Microsoft.UI.Text.TextSetOptions.FormatRtf, string.Empty);
}
}
catch (Exception ex)
{
// 处理异常,例如记录日志或显示错误消息
Debug.WriteLine($"Error loading RTF file: {ex.Message}");
DescriptionRichEditBox.Document.SetText(Microsoft.UI.Text.TextSetOptions.FormatRtf, string.Empty);
}
RatingChoose.Value = ErrorItem.Rating;
DisplayFilesIcon();
}
}
// 离开后取消订阅
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
if (ErrorItem != null && ErrorItem.TagItems != null)
{
ErrorItem.TagItems.CollectionChanged -= TagItems_CollectionChanged;
}
}
// 选择文件按钮点击事件
private async void OnSelectFileClick(object sender, RoutedEventArgs e)
{
try
{
var picker = new FileOpenPicker
{
SuggestedStartLocation = PickerLocationId.Desktop,
CommitButtonText = "Upload 上传",
};
picker.FileTypeFilter.Add("*");
var hwnd = WinRT.Interop.WindowNative.GetWindowHandle(App.MainWindow);
WinRT.Interop.InitializeWithWindow.Initialize(picker, hwnd);
var files = await picker.PickMultipleFilesAsync();
if (files != null && files.Count > 0)
{
var filesFolder = Path.Combine(appDataPath, "Files");
Directory.CreateDirectory(filesFolder);
foreach (var file in files)
{
var destinationPath = Path.Combine(filesFolder, file.Name);
// 检查目标文件是否存在,避免覆盖
if (File.Exists(destinationPath))
{
string uniqueFileName = $"{Path.GetFileNameWithoutExtension(file.Name)}_{Guid.NewGuid()}{Path.GetExtension(file.Name)}";
destinationPath = Path.Combine(filesFolder, uniqueFileName);
}
await file.CopyAsync(await StorageFolder.GetFolderFromPathAsync(filesFolder), Path.GetFileName(destinationPath), NameCollisionOption.GenerateUniqueName);
ErrorItem.FilePaths.Add(destinationPath);
}
DisplayFilesIcon();
await SaveCurrentContentAsync();
}
}
catch (Exception ex)
{
// 处理异常,例如记录日志或显示错误消息
await ShowErrorMessageAsync(ex);
}
}
// 从剪切板上传玩意儿
private async void OpenFromClipboardClick(object sender, RoutedEventArgs e)
{
try
{
// 确保本地文件夹存在
var filesFolder = Path.Combine(appDataPath, "Files");
Directory.CreateDirectory(filesFolder);
var dataPackageView = Clipboard.GetContent();
if (dataPackageView == null)
{
throw new InvalidOperationException("Clipboard content is null.");
}
// 获取(多个)文件
if (dataPackageView.Contains(StandardDataFormats.StorageItems))
{
var items = await dataPackageView.GetStorageItemsAsync();
if (items.Count > 0)
{
foreach (var item in items)
{
var storageFile = item as StorageFile;
if (storageFile != null)
{
string destinationPath = Path.Combine(filesFolder, storageFile.Name);
// 检查目标文件是否存在,避免覆盖
if (File.Exists(destinationPath))
{
string uniqueFileName = $"{Path.GetFileNameWithoutExtension(storageFile.Name)}_{Guid.NewGuid()}{Path.GetExtension(storageFile.Name)}";
destinationPath = Path.Combine(filesFolder, uniqueFileName);
}
await SaveFileToFixedPathAsync(storageFile, destinationPath);
ErrorItem.FilePaths.Add(destinationPath);
}
}
DisplayFilesIcon();
}
}
// 获取截图
else if (dataPackageView.Contains(StandardDataFormats.Bitmap))
{
var bitmap = await dataPackageView.GetBitmapAsync();
if (bitmap != null)
{
using (IRandomAccessStream stream = await bitmap.OpenReadAsync())
{
string uniqueFileName = $"Image_{Guid.NewGuid()}.png";
string destinationPath = Path.Combine(filesFolder, uniqueFileName);
await SaveStreamToFileAsync(stream, destinationPath);
ErrorItem.FilePaths.Add(destinationPath);
}
DisplayFilesIcon();
}
}
// 获取复制的文本
else if (dataPackageView.Contains(StandardDataFormats.Text))
{
var text = await dataPackageView.GetTextAsync();
if (!string.IsNullOrEmpty(text))
{
string uniqueFileName = $"Text_{Guid.NewGuid()}.txt";
string destinationPath = Path.Combine(filesFolder, uniqueFileName);
await CreateTextFileWithFileNamesAsync(destinationPath, text);
ErrorItem.FilePaths.Add(destinationPath);
DisplayFilesIcon();
}
}
else
{
var dialog = new ContentDialog
{
XamlRoot = this.Content.XamlRoot,
Title = "Error 错误",
Content = "No images found 剪贴板中没有图像。",
CloseButtonText = "Ok 确定",
FontFamily = (FontFamily)Application.Current.Resources["FontRegular"],
// RequestedTheme = (ElementTheme)Application.Current.RequestedTheme // 设置主题与应用程序一致
Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style
};
await dialog.ShowAsync();
}
await SaveCurrentContentAsync();
}
catch (Exception ex)
{
// 处理异常,例如记录日志或显示错误消息
await ShowErrorMessageAsync(ex);
}
}
// 显示文件图标
private void DisplayFilesIcon()
{
FilePanel.Items.Clear();
foreach (var filePath in ErrorItem.FilePaths)
{
var fileName = Path.GetFileName(filePath);
var fileType = Path.GetExtension(filePath).ToLower();
var bitmapImage = new BitmapImage();
switch (fileType)
{
case ".docx":
case ".doc":
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/word.png"));
break;
case ".pptx":
case ".ppt":
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/powerpoint.png"));
break;
case ".xlsx":
case ".xls":
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/excel.png"));
break;
case ".pdf":
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/pdf.png"));
break;
case ".txt":
case ".md":
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/text.png"));
break;
case ".zip":
case ".rar":
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/zip.png"));
break;
case ".xmind":
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/xmind.png"));
break;
case ".mp3":
case ".mp4":
case ".mkv":
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/video.png"));
break;
case ".jpg":
case ".jpeg":
case ".png":
case ".bmp":
case ".gif":
case ".ico":
// 清空图片缓存并重新加载图片
bitmapImage.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bitmapImage.UriSource = new Uri(filePath);
break;
default:
bitmapImage = new BitmapImage(new Uri("ms-appx:///Assets/unknown.png"));
break;
}
var image = new Microsoft.UI.Xaml.Controls.Image
{
Source = bitmapImage,
Width = 100,
Height = 100,
Tag = filePath, // 将文件路径存储在Tag中,即使是文件图标,也会传递着文件的路径
};
image.Tapped += File_Tapped;
// 创建右键菜单
var contextMenu = new MenuFlyout();
// 菜单1 复制文件
var copyItem = new MenuFlyoutItem { Text = "Copy 复制", FontFamily = (FontFamily)Application.Current.Resources["FontRegular"] };
copyItem.Click += (sender, e) => CopyFile(filePath);
contextMenu.Items.Add(copyItem);
// 菜单2 删除
var deleteItem = new MenuFlyoutItem { Text = "Delete 删除", FontFamily = (FontFamily)Application.Current.Resources["FontRegular"] };
deleteItem.Click += (sender, e) => DeleteImage(filePath);
contextMenu.Items.Add(deleteItem);
// 设置右键菜单
image.ContextFlyout = contextMenu;
var fileNameBlock = new TextBlock
{
Text = fileName,
Width = 120,
TextWrapping = TextWrapping.Wrap,
TextAlignment = TextAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
FontSize = 12,
Margin = new Thickness(0, 5, 0, 0),
FontFamily = (FontFamily)Application.Current.Resources["FontRegular"],
};
var contentPanel = new StackPanel
{
HorizontalAlignment = HorizontalAlignment.Center,
};
contentPanel.Children.Add(image);
contentPanel.Children.Add(fileNameBlock);
contentPanel.Margin = new Thickness(5);
FilePanel.Items.Add(contentPanel);
}
}
// 右键菜单 删除单个文件
private async void DeleteImage(string filePath)
{
try
{
// 从 ErrorItem.FilePaths 中移除文件路径
ErrorItem.FilePaths.Remove(filePath);
// 删除本地文件
if (File.Exists(filePath))
{
File.Delete(filePath);
}
// 重新显示文件图标
DisplayFilesIcon();
await SaveCurrentContentAsync();
}
catch (Exception ex)
{
await ShowErrorMessageAsync(ex);
}
}
// 右键菜单 复制单个文件
private async void CopyFile(string filePath)
{
try
{
var file = await StorageFile.GetFileFromPathAsync(filePath);
if (file == null)
{
throw new FileNotFoundException("File not found.", filePath);
}
var dataPackage = new DataPackage();
dataPackage.SetStorageItems(new List<IStorageItem> { file });
Clipboard.SetContent(dataPackage);
}
catch (Exception ex)
{
await ShowErrorMessageAsync(ex);
}
}
// 点击文件图标 判断是dialog还是直接打开
private async void File_Tapped(object sender, TappedRoutedEventArgs e)
{
try
{
if (sender is Microsoft.UI.Xaml.Controls.Image image && image.Tag is string filePath)
{
var fileType = Path.GetExtension(filePath).ToLower();
// 显示预览图片
if (fileType == ".jpg" || fileType == ".jpeg" || fileType == ".png" || fileType == ".bmp" || fileType == ".gif" || fileType == ".ico")
{
BitmapImage bitmap = new BitmapImage(new Uri(filePath, UriKind.RelativeOrAbsolute));
bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bitmap.UriSource = new Uri(filePath);
dialogImage = new Microsoft.UI.Xaml.Controls.Image
{
Source = bitmap,
Tag = filePath
};
Dialog.Content = dialogImage;
Dialog.Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style;
// Dialog.RequestedTheme = (ElementTheme)Application.Current.RequestedTheme; // 设置主题与应用程序一致
await Dialog.ShowAsync();
}
// 显示预览txt文件
else if (fileType == ".txt")
{
var file = await StorageFile.GetFileFromPathAsync(filePath);
var texts = await FileIO.ReadTextAsync(file);
dialogTextBlock = new TextBlock()
{
Text = texts,
Tag = filePath,
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(10),
IsTextSelectionEnabled = true,
FontFamily = (FontFamily)Application.Current.Resources["FontRegular"]
};
var textBlockScrollViewer = new ScrollViewer
{
VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
Content = dialogTextBlock,
};
Dialog.Content = textBlockScrollViewer;
Dialog.Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style;
// Dialog.RequestedTheme = (ElementTheme)Application.Current.RequestedTheme; // 设置主题与应用程序一致
await Dialog.ShowAsync();
}
// 预览播放视频或音频
else if (fileType == ".mp3" || fileType == ".mp4" || fileType == ".mkv")
{
var file = await StorageFile.GetFileFromPathAsync(filePath);
dialogMediaPlayer = new MediaPlayerElement
{
AreTransportControlsEnabled = true,
Source = MediaSource.CreateFromUri(new Uri(filePath)),
AutoPlay = false,
Height = Double.NaN,
Tag = filePath
};
Dialog.Content = dialogMediaPlayer;
Dialog.Closed += mediaDialog_Closed;
Dialog.Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style;
// Dialog.RequestedTheme = (ElementTheme)Application.Current.RequestedTheme; // 设置主题与应用程序一致;
await Dialog.ShowAsync();
}
// 以默认方式打开其他类型的文件
else
{
var file = await StorageFile.GetFileFromPathAsync(filePath);
if (file != null)
{
await Launcher.LaunchFileAsync(file);
}
}
}
}
catch (Exception ex)
{
// 处理异常,例如记录日志或显示错误消息
await ShowErrorMessageAsync(ex);
}
}
// 关掉媒体播放对话框
private void mediaDialog_Closed(ContentDialog sender, ContentDialogClosedEventArgs args)
{
if (dialogMediaPlayer != null)
{
var playbackState = dialogMediaPlayer.MediaPlayer.PlaybackSession.PlaybackState;
dialogMediaPlayer.MediaPlayer.Pause();
}
}
// 以默认方式打开
private async void OpenFileInSystemClick(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
try
{
string filePath = null;
// 需要在每次的dialog关闭的时候,把dialogImage、dialogTextBlock、dialogMediaPlayer置空
// 不然dialogImage每次都会覆盖下面的textblock和mediaplayer
if (dialogImage != null && dialogImage.Tag is string imagePath)
{
filePath = imagePath;
}
else if (dialogTextBlock != null && dialogTextBlock.Tag is string textBlockPath)
{
filePath = textBlockPath;
}
else if (dialogMediaPlayer != null && dialogMediaPlayer.Tag is string mediaPath)
{
filePath = mediaPath;
}
if (filePath != null)
{
var file = await StorageFile.GetFileFromPathAsync(filePath);
if (file != null)
{
await Launcher.LaunchFileAsync(file);
}
}
}
catch (Exception ex)
{
// 处理异常,例如记录日志或显示错误消息
await ShowErrorMessageAsync(ex);
}
finally
{
dialogImage = null;
dialogTextBlock = null;
dialogMediaPlayer = null;
}
}
// 点击保存页面
private async void OnSaveClick(object sender, RoutedEventArgs e)
{
try
{
await SaveCurrentContentAsync();
PublicEvents.PlaySystemSound();
ContentDialog saveSuccess = new ContentDialog()
{
XamlRoot = rootPanel.XamlRoot,
Title = "Saved 已保存",
Content = "Save successfully 保存成功!",
CloseButtonText = "Ok",
DefaultButton = ContentDialogButton.Close,
FontFamily = (FontFamily)Application.Current.Resources["FontRegular"],
// RequestedTheme = (ElementTheme)Application.Current.RequestedTheme // 设置主题与应用程序一致
Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style
};
await saveSuccess.ShowAsync();
}
catch (Exception ex)
{
// 处理异常,例如记录日志或显示错误消息
await ShowErrorMessageAsync(ex);
}
}
// 点击删除页面
private async void DeleteClick(object sender, RoutedEventArgs e)
{
ContentDialog confirmDialog = new ContentDialog
{
Title = "Confirm to delete 确认删除",
Content = "Are you sure to delete this page forever? 你确定要删除这一页吗?",
PrimaryButtonText = "Yes 是",
CloseButtonText = "No 否",
DefaultButton = ContentDialogButton.Close,
XamlRoot = this.Content.XamlRoot,
FontFamily = (FontFamily)Application.Current.Resources["FontRegular"],
Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style
};
var result = await confirmDialog.ShowAsync();
if (result == ContentDialogResult.Primary)
{
try
{
// 删除本地Files里的对应文件
foreach (var filePath in ErrorItem.FilePaths)
{
if (File.Exists(filePath))
{
File.Delete(filePath);
}
}
// 删除本地rtfFiles里的对应文件
string rtfFilePath = Path.Combine(appDataPath, "rtfFiles", $"{ErrorItem.Id}.rtf");
if (File.Exists(rtfFilePath))
{
File.Delete(rtfFilePath);
}
var mainWindow = (MainWindow)App.MainWindow;
mainWindow.RemoveNavigationViewItem(ErrorItem); // 给navigationView传递要删除的当前的ErrorItem
}
catch (Exception ex)
{
// 处理异常,例如记录日志或显示错误消息
await ShowErrorMessageAsync(ex);
}
}
}
// 日期设置为今天
private void SetDateToTodayClick(object sender, RoutedEventArgs e)
{
DatePicker.Date = DateTime.Now;
}
// 保存当前内容
public async Task SaveCurrentContentAsync()
{
try
{
StorageFolder localFolder = await StorageFolder.GetFolderFromPathAsync(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "ElectronicCorrectionNotebook"));
StorageFolder rtfFolder = await localFolder.CreateFolderAsync("rtfFiles", CreationCollisionOption.OpenIfExists);
string rtfFileName = $"{ErrorItem.Id}.rtf";
StorageFile rtfFile = await rtfFolder.CreateFileAsync(rtfFileName, CreationCollisionOption.ReplaceExisting);
// 保存 RichEditBox 的内容到 RTF 文件
using (var stream = await rtfFile.OpenAsync(FileAccessMode.ReadWrite))
{
DescriptionRichEditBox.Document.SaveToStream(Microsoft.UI.Text.TextGetOptions.FormatRtf, stream);
}
// 调用 MainWindow 的 SaveDataAsync 方法保存整个集合
var mainWindow = (MainWindow)App.MainWindow;
await mainWindow.SaveDataAsync(cts.Token);
}
catch (OperationCanceledException)
{
// Handle cancellation
}
catch (Exception ex)
{
// 处理其他异常,例如记录日志或显示错误消息
await ShowErrorMessageAsync(ex);
}
}
// 显示错误消息
private async Task ShowErrorMessageAsync(Exception ex)
{
var errorDialog = new ContentDialog()
{
XamlRoot = this.Content.XamlRoot,
Title = "Error!",
Content = ex.Message,
CloseButtonText = "Ok 确定",
FontFamily = (FontFamily)Application.Current.Resources["FontRegular"],
Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style
};
await errorDialog.ShowAsync();
}
// 把剪切板的文件复制到Files文件夹(可操作任意文件)
private async Task SaveFileToFixedPathAsync(StorageFile sourceFile, string destinationPath)
{
var destinationFolder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(destinationPath));
var destinationFile = await destinationFolder.CreateFileAsync(Path.GetFileName(destinationPath), CreationCollisionOption.ReplaceExisting);
await sourceFile.CopyAndReplaceAsync(destinationFile);
}
// 把剪切板的Bitmap复制到Files文件夹(仅限截图)
private async Task SaveStreamToFileAsync(IRandomAccessStream stream, string filePath)
{
var folder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(filePath));
var file = await folder.CreateFileAsync(Path.GetFileName(filePath), CreationCollisionOption.ReplaceExisting);
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await RandomAccessStream.CopyAndCloseAsync(stream.GetInputStreamAt(0), fileStream.GetOutputStreamAt(0));
}
}
// 创建txt文本文件
private async Task CreateTextFileWithFileNamesAsync(string filePath, string text_Content)
{
var folder = await StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(filePath));
var file = await folder.CreateFileAsync(Path.GetFileName(filePath), CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(file, text_Content);
}
// 刷新按钮点击事件
private void RefreshButton_Click(object sender, RoutedEventArgs e)
{
DisplayFilesIcon();
}
#region RichEditBox Settings
// 粗体按钮
private void BoldButton_Click(object sender, RoutedEventArgs e)
{
DescriptionRichEditBox.Document.Selection.CharacterFormat.Bold = Microsoft.UI.Text.FormatEffect.Toggle;
}
// 斜体按钮
private void ItalicButton_Click(object sender, RoutedEventArgs e)
{
DescriptionRichEditBox.Document.Selection.CharacterFormat.Italic = Microsoft.UI.Text.FormatEffect.Toggle;
}
// 下划线按钮
private void UnderlineButton_Click(object sender, RoutedEventArgs e)
{
var selection = DescriptionRichEditBox.Document.Selection;
if (selection.CharacterFormat.Underline == Microsoft.UI.Text.UnderlineType.None)
{
selection.CharacterFormat.Underline = Microsoft.UI.Text.UnderlineType.Single;
}
else
{
selection.CharacterFormat.Underline = Microsoft.UI.Text.UnderlineType.None;
}
}
// 字体颜色
private void ColorButton_Click(object sender, RoutedEventArgs e)
{
Button clickedColor = (Button)sender;
var rectangle = (Microsoft.UI.Xaml.Shapes.Rectangle)clickedColor.Content;
var color = ((Microsoft.UI.Xaml.Media.SolidColorBrush)rectangle.Fill).Color;
if (sender is Button btn && btn.Content is Microsoft.UI.Xaml.Shapes.Rectangle rect && rect.Fill is SolidColorBrush brush)
{
SelectedFontColor = brush;
}
DescriptionRichEditBox.Document.Selection.CharacterFormat.ForegroundColor = color;
fontColorButton.Flyout.Hide();
DescriptionRichEditBox.Focus(Microsoft.UI.Xaml.FocusState.Keyboard);
}
// 高亮颜色
private void HighlightButton_Click(object sender, RoutedEventArgs e)
{
Button clickedColor = (Button)sender;
var rectangle = (Microsoft.UI.Xaml.Shapes.Rectangle)clickedColor.Content;
var color = ((Microsoft.UI.Xaml.Media.SolidColorBrush)rectangle.Fill).Color;
if (sender is Button btn && btn.Content is Microsoft.UI.Xaml.Shapes.Rectangle rect && rect.Fill is SolidColorBrush brush)
{
SelectedHLColor = brush;
}
DescriptionRichEditBox.Document.Selection.CharacterFormat.BackgroundColor = color;
fontColorButton.Flyout.Hide();
DescriptionRichEditBox.Focus(Microsoft.UI.Xaml.FocusState.Keyboard);
}
#endregion
#region TokenizingTextBox
// 添加Tag
private async void TokenBox_TokenItemAdding(object sender, TokenItemAddingEventArgs e)
{
// 去除输入文本的前后空格
string tokenText = e.TokenText.Trim();
// 检查标签是否已存在
bool isDuplicate = ErrorItem.TagItems
.Any(item => string.Equals(item.Name, tokenText, StringComparison.Ordinal));
if (isDuplicate)
{
// 如果存在重复,则取消添加
e.Cancel = true;
// 可选:向用户显示提示消息
var duplicateDialog = new ContentDialog
{
XamlRoot = this.Content.XamlRoot,
Title = "Repetition 重复标签",
Content = $"Tag 标签 \"{tokenText}\" 已存在",
CloseButtonText = "Ok 确定",
FontFamily = (FontFamily)Application.Current.Resources["FontRegular"],
Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style
};
await duplicateDialog.ShowAsync();
}
else
{
// 如果不存在,则创建并添加新的标签项
var newTag = new TagItem
{
Name = tokenText
};
// **关键:设置 e.Item,以便 TokenizingTextBox 知道要添加的项**
e.Item = newTag;
// 临时解决方案
// 更新 SuggestedTagList
/*if (!MainWindowInstance.SuggestedTagList
.Any(tag => string.Equals(tag.Name, newTag.Name, StringComparison.OrdinalIgnoreCase)))
{
MainWindowInstance.SuggestedTagList.Add(newTag);
}*/
}
}
// 更改建议列表
private void TagTextBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs e)
{
string enteredText = sender.Text.Trim();
// 清空现有的过滤结果
FilteredSuggestedTags.Clear();
IEnumerable<TagItem> filtered;
if (string.IsNullOrEmpty(enteredText))
{
// 如果输入为空,显示完整的建议列表
filtered = MainWindowInstance.SuggestedTagList;
}
else
{
// 根据输入过滤建议列表
filtered = MainWindowInstance.SuggestedTagList
.Where(tag => tag.Name.IndexOf(enteredText, StringComparison.OrdinalIgnoreCase) >= 0);
}
// 添加过滤后的结果
foreach (var tag in filtered)
{
FilteredSuggestedTags.Add(tag);
}
}
#endregion
}
}