-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMainWindow.xaml.cs
406 lines (351 loc) · 14 KB
/
MainWindow.xaml.cs
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
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Media;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ElectronicCorrectionNotebook.Services;
using System.Threading;
using Microsoft.UI.Xaml.Documents;
using Microsoft.UI.Xaml.Media.Imaging;
using Windows.ApplicationModel.Core;
using Microsoft.UI;
using System.Runtime.InteropServices;
using WinRT;
using PInvoke;
using ElectronicCorrectionNotebook.DataStructure;
using Microsoft.UI.Xaml.Data;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Linq;
namespace ElectronicCorrectionNotebook
{
public sealed partial class MainWindow : Window
{
public ObservableCollection<ErrorItem> ErrorItems { get; set; } = new ObservableCollection<ErrorItem>();
// Suggested Tags 只存在一次的
private ObservableCollection<TagItem> suggestedTagList { get; set; } = new ObservableCollection<TagItem>();
public ObservableCollection<TagItem> SuggestedTagList
{
get => suggestedTagList;
set
{
if (suggestedTagList != value)
{
suggestedTagList = value;
OnPropertyChanged();
}
}
}
private CancellationTokenSource cts;
private const int MinWidth = 1250; // 设置最小宽度
private const int MinHeight = 1250; // 设置最小高度
private Microsoft.UI.Windowing.AppWindow appWindow;
public MainWindow()
{
InitializeComponent();
var micaBackdrop = new Microsoft.UI.Xaml.Media.MicaBackdrop();
micaBackdrop.Kind = Microsoft.UI.Composition.SystemBackdrops.MicaKind.BaseAlt;
// var acry = new Microsoft.UI.Xaml.Media.DesktopAcrylicBackdrop();
this.SystemBackdrop = micaBackdrop;
SubClassing();
Closed += MainWindow_Closed;
CoreApplication.Exiting += OnExiting;
var hWnd = WinRT.Interop.WindowNative.GetWindowHandle(this);
var windowId = Microsoft.UI.Win32Interop.GetWindowIdFromWindow(hWnd);
appWindow = Microsoft.UI.Windowing.AppWindow.GetFromWindowId(windowId);
appWindow.SetIcon("Assets/im.ico");
cts = new CancellationTokenSource();
_ = LoadDataAsync(cts.Token);
ExtendsContentIntoTitleBar = true;
SetTitleBar(AppTitleBar);
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
// 临时解决方案
/*public void UpdateSuggestedTagList()
{
SuggestedTagList.Clear();
foreach (var item in ErrorItems)
{
foreach (var tag in item.TagItems)
{
if (!SuggestedTagList.Contains(tag))
{
SuggestedTagList.Add(tag);
}
}
}
}*/
// 加载数据-从json中读取数据+制作suggestedTagList
public async Task LoadDataAsync(CancellationToken token)
{
try
{
var items = await DataService.LoadDataAsync(token);
foreach (var item in items)
{
ErrorItems.Add(item);
foreach (var tagItem in item.TagItems)
{
// 会有重复
/*if (!SuggestedTagList.Contains(tag))
{
SuggestedTagList.Add(tag);
}*/
if (!SuggestedTagList.Any(tag => string.Equals(tag.Name, tagItem.Name, StringComparison.Ordinal)))
{
SuggestedTagList.Add(tagItem);
}
}
}
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
await ShowErrorMessageAsync(ex);
}
}
// 存储数据-把数据存储到json-调用DataServie
public async Task SaveDataAsync(CancellationToken token)
{
try
{
await DataService.SaveDataAsync(ErrorItems, token);
}
catch (OperationCanceledException)
{
// Handle cancellation
}
catch (Exception ex)
{
await ShowErrorMessageAsync(ex);
}
}
// 添加新错题-总步骤
private async void Add_Tapped(object sender, TappedRoutedEventArgs e)
{
var newErrorItem = new ErrorItem
{
Title = "New Error",
Date = DateTime.Now,
FilePaths = new List<string>(),
Rating = -1,
};
ErrorItems.Add(newErrorItem);
await SaveDataAsync(cts.Token);
}
// 关于
private async void About_Tapped(object sender, TappedRoutedEventArgs e)
{
PublicEvents.PlaySystemSound();
StackPanel contentPanel = new StackPanel();
TextBlock aboutInfo = new TextBlock()
{
TextWrapping = TextWrapping.Wrap,
Margin = new Thickness(0, 10, 0, 0)
};
aboutInfo.Inlines.Add(new Run { Text = "Created by " });
Hyperlink hyperlink = new Hyperlink();
hyperlink.Inlines.Add(new Run { Text = "@QuincyZhao😀" });
hyperlink.NavigateUri = new Uri("https://github.com/zhaoqianbiao");
hyperlink.Foreground = new SolidColorBrush(Microsoft.UI.Colors.OrangeRed);
aboutInfo.Inlines.Add(hyperlink);
aboutInfo.Inlines.Add(new Run { Text = " in GCGS" });
aboutInfo.FontFamily = (FontFamily)Application.Current.Resources["FontRegular"];
Image aboutImage = new Image()
{
Source = new BitmapImage(new Uri("ms-appx:///Assets/peter.png")),
Width = 100,
Height = 100,
Margin = new Thickness(0, 10, 0, 0)
};
contentPanel.Children.Add(aboutInfo);
contentPanel.Children.Add(aboutImage);
ContentDialog about = new ContentDialog()
{
XamlRoot = this.Content.XamlRoot,
Title = "About",
FontFamily = (FontFamily)Application.Current.Resources["FontBold"],
Content = contentPanel,
CloseButtonText = "Ok",
// RequestedTheme = (ElementTheme)Application.Current.RequestedTheme // 设置主题与应用程序一致
Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style
};
await about.ShowAsync();
}
// 导航视图选择更改时
public async void NavigationView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args)
{
if (contentFrame.Content is ErrorDetailPage currentPage)
{
await currentPage.SaveCurrentContentAsync();
}
if (args.IsSettingsSelected)
{
contentFrame.Navigate(typeof(SettingsPage));
}
else if (args.SelectedItem != null)
{
var selectedErrorItem = args.SelectedItem as ErrorItem;
if (selectedErrorItem != null)
{
contentFrame.Navigate(typeof(ErrorDetailPage), selectedErrorItem);
}
}
}
// 窗口关闭时
public async void MainWindow_Closed(object sender, WindowEventArgs args)
{
await SaveCurrentStateAsync();
this.Closed -= MainWindow_Closed;
Application.Current.Exit();
}
// 应用程序退出时
private async void OnExiting(object sender, object e)
{
await SaveCurrentStateAsync();
}
// 保存当前状态
private async Task SaveCurrentStateAsync()
{
if (contentFrame.Content is ErrorDetailPage currentPage)
{
await currentPage.SaveCurrentContentAsync();
}
await SaveDataAsync(cts.Token);
cts.Cancel();
}
// 删除项-不用改
public async void RemoveNavigationViewItem(ErrorItem errorItem)
{
ErrorItems.Remove(errorItem);
await SaveDataAsync(cts.Token);
contentFrame.Content = null;
}
// 跳转的时候 自动选中对应的item
private void SelectNavigationViewItem(ErrorItem errorItem)
{
nvSample.SelectedItem = errorItem;
}
// 显示错误消息
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"],
// RequestedTheme = (ElementTheme)Application.Current.RequestedTheme // 设置主题与应用程序一致
Style = Application.Current.Resources["DefaultContentDialogStyle"] as Style
};
await errorDialog.ShowAsync();
}
#region AutoSuggestBoxCodeRegion
// 在搜索框中输入的时候更改建议列表
public void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
{
if (args.Reason == AutoSuggestionBoxTextChangeReason.UserInput)
{
var suggestions = new List<string>();
foreach (var item in ErrorItems)
{
if (item.Title.Contains(sender.Text, StringComparison.OrdinalIgnoreCase))
{
suggestions.Add(item.Title);
}
}
sender.ItemsSource = suggestions;
sender.FontFamily = (FontFamily)Application.Current.Resources["FontRegular"];
}
}
// 点击某一项后,跳转到某一个页面
public void AutoSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
{
if (args.ChosenSuggestion != null)
{
foreach (var item in ErrorItems)
{
if (item.Title == (string)args.ChosenSuggestion)
{
SelectNavigationViewItem(item); // 自动选中对应的item
break;
}
}
}
else if (!string.IsNullOrEmpty(args.QueryText))
{
foreach (var item in ErrorItems)
{
if (item.Title == args.QueryText)
{
SelectNavigationViewItem(item); // 自动选中对应的item
break;
}
}
}
}
// 确认点击某一项后,搜索栏中显示那一项的名称
public void AutoSuggestBox_SuggestionChosen(AutoSuggestBox sender, AutoSuggestBoxSuggestionChosenEventArgs args)
{
sender.Text = args.SelectedItem.ToString();
}
#endregion
#region MinMaxCodeRegion
private delegate IntPtr WinProc(IntPtr hWnd, User32.WindowMessage Msg, IntPtr wParam, IntPtr lParam);
private WinProc newWndProc = null;
private IntPtr oldWndProc = IntPtr.Zero;
[DllImport("user32.dll", SetLastError = true)]
private static extern IntPtr SetWindowLongPtr(IntPtr hWnd, User32.WindowLongIndexFlags nIndex, WinProc newProc);
[DllImport("user32.dll")]
private static extern IntPtr CallWindowProc(IntPtr lpPrevWndFunc, IntPtr hWnd, User32.WindowMessage Msg, IntPtr wParam, IntPtr lParam);
private void SubClassing()
{
// Get the Window's HWND
var hwnd = this.As<IWindowNative>().WindowHandle;
newWndProc = new WinProc(NewWindowProc);
oldWndProc = SetWindowLongPtr(hwnd, User32.WindowLongIndexFlags.GWL_WNDPROC, newWndProc);
}
[StructLayout(LayoutKind.Sequential)]
struct MINMAXINFO
{
public POINT ptReserved;
public POINT ptMaxSize;
public POINT ptMaxPosition;
public POINT ptMinTrackSize;
public POINT ptMaxTrackSize;
}
private IntPtr NewWindowProc(IntPtr hWnd, User32.WindowMessage Msg, IntPtr wParam, IntPtr lParam)
{
switch (Msg)
{
case User32.WindowMessage.WM_GETMINMAXINFO:
var dpi = User32.GetDpiForWindow(hWnd);
// float scalingFactor = (float)dpi / 96;
MINMAXINFO minMaxInfo = Marshal.PtrToStructure<MINMAXINFO>(lParam);
minMaxInfo.ptMinTrackSize.x = (int)(MinWidth);
minMaxInfo.ptMinTrackSize.y = (int)(MinHeight);
Marshal.StructureToPtr(minMaxInfo, lParam, true);
break;
}
return CallWindowProc(oldWndProc, hWnd, Msg, wParam, lParam);
}
[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("EECDBF0E-BAE9-4CB6-A68E-9598E1CB57BB")]
internal interface IWindowNative
{
IntPtr WindowHandle { get; }
}
#endregion
}
}