mirror of
https://github.com/real-zony/ZonyLrcToolsX.git
synced 2026-11-24 03:37:47 +08:00
refactor(desktop): 页面切换统一走 INavigationService
侧栏原先是在 MainWindow.axaml.cs 里用一个针对 ListBox.SelectedIndex 的 switch 接起来的,直接调 App.Services.GetRequiredService<...> 从 code-behind 赋页面。 NavigationService 存在、已注册,却从没被用过。 后果:首页的深层链接无法改变侧栏选中项;新增一个页面要同时改 view model 和 code-behind;每个页面即使该是单例也会被重新构造。 现在: - INavigationService 增加 NavigateRoot<T>(),用于"跳到顶层页面"(清空回退栈), 与已有的 NavigateTo<T>()、GoBack() 并存。 - MainWindowViewModel 订阅 NavigationChanged,把当前 view model 反映射成侧栏 索引,因此从首页卡片跳转时侧栏高亮会跟着走。 - MainWindow.axaml.cs 基本清空;ListBox 绑索引,导航由 view model 发起。 这个提交里两处对话框服务的新增是给后面页面用的: - ShowFilesPickerAsync —— 多选,解密页需要 - ShowQrCodeLoginDialogAsync —— 把网易云二维码对话框作为模态窗口承载 - ShowMessageAsync 补进接口。它早已实现、也早已被调用,只是没写进契约。
This commit is contained in:
1 parent
9cda87dbfe
commit
216ea4e0c4
8 files changed
+239
-46
No files matched your search
@@ -2,6 +2,7 @@ using Avalonia;
|
||||
using Avalonia.Controls;
|
||||
using Avalonia.Controls.ApplicationLifetimes;
|
||||
using Avalonia.Platform.Storage;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
using ZonyLrcTools.Desktop.Views.Dialogs;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Services;
|
||||
@@ -28,22 +29,58 @@ public class DialogService : IDialogService
|
||||
|
||||
public async Task<string?> ShowFilePickerAsync(string title, string[]? filters = null)
|
||||
{
|
||||
if (MainWindow == null) return null;
|
||||
var files = await ShowFilesPickerAsync(title, filters);
|
||||
return files.FirstOrDefault();
|
||||
}
|
||||
|
||||
var fileTypes = filters?.Select(f => new FilePickerFileType(f)
|
||||
{
|
||||
Patterns = new[] { f }
|
||||
}).ToList();
|
||||
public async Task<IReadOnlyList<string>> ShowFilesPickerAsync(string title, string[]? filters = null)
|
||||
{
|
||||
if (MainWindow == null) return Array.Empty<string>();
|
||||
|
||||
var fileTypes = BuildFileTypes(filters);
|
||||
|
||||
var files = await MainWindow.StorageProvider.OpenFilePickerAsync(
|
||||
new FilePickerOpenOptions
|
||||
{
|
||||
Title = title,
|
||||
AllowMultiple = false,
|
||||
AllowMultiple = true,
|
||||
FileTypeFilter = fileTypes
|
||||
});
|
||||
|
||||
return files.FirstOrDefault()?.Path.LocalPath;
|
||||
return files
|
||||
.Select(f => f.Path.LocalPath)
|
||||
.Where(p => !string.IsNullOrEmpty(p))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Turn a list of bare extensions (".mp3", "mp3", "*.mp3") into Avalonia file type filters.
|
||||
/// </summary>
|
||||
private static List<FilePickerFileType>? BuildFileTypes(string[]? filters)
|
||||
{
|
||||
if (filters == null || filters.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var patterns = filters
|
||||
.Where(f => !string.IsNullOrWhiteSpace(f))
|
||||
.Select(f => f.StartsWith('*') ? f : $"*.{f.TrimStart('.')}")
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
|
||||
if (patterns.Length == 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var name = string.Join(" / ", patterns.Select(p => p.TrimStart('*', '.')));
|
||||
|
||||
return new List<FilePickerFileType>
|
||||
{
|
||||
new(name) { Patterns = patterns },
|
||||
new("All files") { Patterns = new[] { "*" } }
|
||||
};
|
||||
}
|
||||
|
||||
public async Task<bool> ShowConfirmDialogAsync(string title, string message)
|
||||
@@ -62,4 +99,16 @@ public class DialogService : IDialogService
|
||||
var dialog = new MessageDialog(title, message);
|
||||
await dialog.ShowDialog(MainWindow);
|
||||
}
|
||||
|
||||
public async Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel)
|
||||
{
|
||||
if (MainWindow == null)
|
||||
{
|
||||
viewModel.RequestClose();
|
||||
return;
|
||||
}
|
||||
|
||||
var dialog = new QrCodeLoginDialog(viewModel);
|
||||
await dialog.ShowDialog(MainWindow);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,23 @@
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Services;
|
||||
|
||||
public interface IDialogService
|
||||
{
|
||||
Task<string?> ShowFolderPickerAsync(string title);
|
||||
|
||||
Task<string?> ShowFilePickerAsync(string title, string[]? filters = null);
|
||||
|
||||
Task<IReadOnlyList<string>> ShowFilesPickerAsync(string title, string[]? filters = null);
|
||||
|
||||
Task<bool> ShowConfirmDialogAsync(string title, string message);
|
||||
|
||||
Task ShowMessageAsync(string title, string message);
|
||||
|
||||
/// <summary>
|
||||
/// Open the NetEase QR-code login dialog as a modal child of the main window.
|
||||
/// The returned task completes when the user or the login flow closes it; callers that
|
||||
/// only want the dialog on screen can ignore it.
|
||||
/// </summary>
|
||||
Task ShowQrCodeLoginDialogAsync(QrCodeLoginViewModel viewModel);
|
||||
}
|
||||
@@ -7,7 +7,17 @@ public interface INavigationService
|
||||
ViewModelBase? CurrentViewModel { get; }
|
||||
event EventHandler<ViewModelBase>? NavigationChanged;
|
||||
|
||||
/// <summary>
|
||||
/// Push a page onto the navigation stack. Use for drill-down (detail pages, wizards).
|
||||
/// </summary>
|
||||
TViewModel NavigateTo<TViewModel>() where TViewModel : ViewModelBase;
|
||||
|
||||
/// <summary>
|
||||
/// Replace the whole stack with a single page. This is what the sidebar uses: switching
|
||||
/// sections is not a back-navigable action, so the stack must not grow on every click.
|
||||
/// </summary>
|
||||
TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase;
|
||||
|
||||
void GoBack();
|
||||
bool CanGoBack { get; }
|
||||
}
|
||||
@@ -22,13 +22,43 @@ public class NavigationService : INavigationService
|
||||
{
|
||||
var viewModel = _serviceProvider.GetRequiredService<TViewModel>();
|
||||
|
||||
if (_navigationStack.TryPeek(out var current))
|
||||
if (_navigationStack.TryPeek(out var current) && ReferenceEquals(current, viewModel))
|
||||
{
|
||||
_ = current.OnDeactivatedAsync();
|
||||
// Already showing this page; do not restart it.
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
if (_navigationStack.TryPeek(out current))
|
||||
{
|
||||
_ = SafeDeactivateAsync(current);
|
||||
}
|
||||
|
||||
_navigationStack.Push(viewModel);
|
||||
_ = viewModel.OnActivatedAsync();
|
||||
_ = SafeActivateAsync(viewModel);
|
||||
|
||||
NavigationChanged?.Invoke(this, viewModel);
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
public TViewModel NavigateRoot<TViewModel>() where TViewModel : ViewModelBase
|
||||
{
|
||||
var viewModel = _serviceProvider.GetRequiredService<TViewModel>();
|
||||
|
||||
if (_navigationStack.Count == 1 && ReferenceEquals(_navigationStack.Peek(), viewModel))
|
||||
{
|
||||
return viewModel;
|
||||
}
|
||||
|
||||
while (_navigationStack.TryPop(out var previous))
|
||||
{
|
||||
if (!ReferenceEquals(previous, viewModel))
|
||||
{
|
||||
_ = SafeDeactivateAsync(previous);
|
||||
}
|
||||
}
|
||||
|
||||
_navigationStack.Push(viewModel);
|
||||
_ = SafeActivateAsync(viewModel);
|
||||
|
||||
NavigationChanged?.Invoke(this, viewModel);
|
||||
return viewModel;
|
||||
@@ -39,12 +69,40 @@ public class NavigationService : INavigationService
|
||||
if (!CanGoBack) return;
|
||||
|
||||
var current = _navigationStack.Pop();
|
||||
_ = current.OnDeactivatedAsync();
|
||||
_ = SafeDeactivateAsync(current);
|
||||
|
||||
if (_navigationStack.TryPeek(out var previous))
|
||||
{
|
||||
_ = previous.OnActivatedAsync();
|
||||
_ = SafeActivateAsync(previous);
|
||||
NavigationChanged?.Invoke(this, previous);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Page lifecycle hooks are fire-and-forget from the caller's perspective; an exception thrown
|
||||
/// inside one must not tear down the navigation call that triggered it.
|
||||
/// </summary>
|
||||
private static async Task SafeActivateAsync(ViewModelBase viewModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
await viewModel.OnActivatedAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// A failing OnActivated must not crash navigation.
|
||||
}
|
||||
}
|
||||
|
||||
private static async Task SafeDeactivateAsync(ViewModelBase viewModel)
|
||||
{
|
||||
try
|
||||
{
|
||||
await viewModel.OnDeactivatedAsync().ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception)
|
||||
{
|
||||
// A failing OnDeactivated must not crash navigation.
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
using ZonyLrcTools.Common.Infrastructure.Logging;
|
||||
using ZonyLrcTools.Common.Infrastructure.Network;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
using ZonyLrcTools.Desktop.Infrastructure.Localization;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
@@ -20,7 +21,10 @@ public static class ServiceCollectionExtensions
|
||||
services.BeginAutoDependencyInject<IWarpHttpClient>();
|
||||
|
||||
// Configure Common services
|
||||
services.ConfigureConfiguration();
|
||||
// ConfigureConfiguration() from Common always reads config.yaml from the executable
|
||||
// folder, which breaks portable installs and read-only install locations. The desktop
|
||||
// app resolves a writable location first and binds from there instead.
|
||||
services.ConfigureDesktopConfiguration();
|
||||
services.ConfigureLocalization();
|
||||
services.ConfigureToolService();
|
||||
|
||||
@@ -39,11 +43,18 @@ public static class ServiceCollectionExtensions
|
||||
services.AddSingleton<IDialogService, DialogService>();
|
||||
services.AddSingleton<IThemeService, ThemeService>();
|
||||
|
||||
// Stores the NetEase login cookie between launches so the QR dialog is a first-run event.
|
||||
services.AddSingleton<NetEaseSessionStore>();
|
||||
|
||||
// Remembers a manually chosen KuGou database path (machine state, not a user preference).
|
||||
services.AddSingleton<KugouDatabaseStore>();
|
||||
|
||||
// Register ViewModels (Singleton to preserve state across navigation)
|
||||
services.AddSingleton<MainWindowViewModel>();
|
||||
services.AddSingleton<HomeViewModel>();
|
||||
services.AddSingleton<LyricsDownloadViewModel>();
|
||||
services.AddSingleton<AlbumDownloadViewModel>();
|
||||
services.AddSingleton<DecryptViewModel>();
|
||||
services.AddSingleton<SettingsViewModel>();
|
||||
|
||||
return services;
|
||||
|
||||
@@ -9,6 +9,7 @@ public partial class MainWindowViewModel : ViewModelBase
|
||||
{
|
||||
private readonly IThemeService _themeService;
|
||||
private readonly IUILocalizationService _localization;
|
||||
private readonly INavigationService _navigation;
|
||||
|
||||
[ObservableProperty]
|
||||
private ViewModelBase? _currentPage;
|
||||
@@ -27,6 +28,7 @@ public partial class MainWindowViewModel : ViewModelBase
|
||||
public string NavHome => _localization["Nav_Home"];
|
||||
public string NavLyricsDownload => _localization["Nav_LyricsDownload"];
|
||||
public string NavAlbumDownload => _localization["Nav_AlbumDownload"];
|
||||
public string NavDecrypt => _localization["Nav_Decrypt"];
|
||||
public string NavSettings => _localization["Nav_Settings"];
|
||||
public string HomeDescription => _localization["Home_Description"];
|
||||
|
||||
@@ -37,25 +39,87 @@ public partial class MainWindowViewModel : ViewModelBase
|
||||
public MainWindowViewModel(
|
||||
IThemeService themeService,
|
||||
IUILocalizationService localization,
|
||||
HomeViewModel homeViewModel)
|
||||
INavigationService navigation)
|
||||
{
|
||||
_themeService = themeService;
|
||||
_localization = localization;
|
||||
_navigation = navigation;
|
||||
|
||||
// Subscribe to language changes
|
||||
_localization.LanguageChanged += OnLanguageChanged;
|
||||
|
||||
// Set initial page
|
||||
CurrentPage = homeViewModel;
|
||||
SelectedNavigationIndex = 0;
|
||||
// The navigation service is the single owner of "which page is showing".
|
||||
_navigation.NavigationChanged += OnNavigationChanged;
|
||||
|
||||
NavigateToIndex(0);
|
||||
}
|
||||
|
||||
// Guards against the re-entrant loop "index changed -> navigate -> navigation changed -> index changed".
|
||||
private bool _isSyncingNavigation;
|
||||
|
||||
partial void OnSelectedNavigationIndexChanged(int value)
|
||||
{
|
||||
if (_isSyncingNavigation)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
NavigateToIndex(value);
|
||||
}
|
||||
|
||||
private void NavigateToIndex(int index)
|
||||
{
|
||||
// NavigateRoot keeps the stack depth at one: sidebar switching is not a back-navigable
|
||||
// action, so clicking around must not grow history.
|
||||
CurrentPage = index switch
|
||||
{
|
||||
1 => _navigation.NavigateRoot<LyricsDownloadViewModel>(),
|
||||
2 => _navigation.NavigateRoot<AlbumDownloadViewModel>(),
|
||||
3 => _navigation.NavigateRoot<DecryptViewModel>(),
|
||||
4 => _navigation.NavigateRoot<SettingsViewModel>(),
|
||||
_ => _navigation.NavigateRoot<HomeViewModel>()
|
||||
};
|
||||
}
|
||||
|
||||
private void OnNavigationChanged(object? sender, ViewModelBase viewModel)
|
||||
{
|
||||
CurrentPage = viewModel;
|
||||
|
||||
// The home page quick actions navigate directly, so the sidebar has to follow them.
|
||||
var index = IndexOf(viewModel);
|
||||
if (index < 0 || index == SelectedNavigationIndex)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isSyncingNavigation = true;
|
||||
try
|
||||
{
|
||||
SelectedNavigationIndex = index;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_isSyncingNavigation = false;
|
||||
}
|
||||
}
|
||||
|
||||
private static int IndexOf(ViewModelBase viewModel) => viewModel switch
|
||||
{
|
||||
LyricsDownloadViewModel => 1,
|
||||
AlbumDownloadViewModel => 2,
|
||||
DecryptViewModel => 3,
|
||||
SettingsViewModel => 4,
|
||||
HomeViewModel => 0,
|
||||
_ => -1
|
||||
};
|
||||
|
||||
private void OnLanguageChanged(object? sender, EventArgs e)
|
||||
{
|
||||
// Notify all localized properties have changed
|
||||
OnPropertyChanged(nameof(NavHome));
|
||||
OnPropertyChanged(nameof(NavLyricsDownload));
|
||||
OnPropertyChanged(nameof(NavAlbumDownload));
|
||||
OnPropertyChanged(nameof(NavDecrypt));
|
||||
OnPropertyChanged(nameof(NavSettings));
|
||||
OnPropertyChanged(nameof(HomeDescription));
|
||||
OnPropertyChanged(nameof(ThemeButtonText));
|
||||
|
||||
@@ -92,8 +92,7 @@
|
||||
<!-- Navigation Menu -->
|
||||
<ListBox Classes="nav-list"
|
||||
SelectedIndex="{Binding SelectedNavigationIndex}"
|
||||
Margin="0,8,0,0"
|
||||
SelectionChanged="OnNavigationSelectionChanged">
|
||||
Margin="0,8,0,0">
|
||||
<ListBoxItem>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<Border Width="3" CornerRadius="1.5"
|
||||
@@ -130,6 +129,18 @@
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</ListBoxItem>
|
||||
<ListBoxItem>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<Border Width="3" CornerRadius="1.5"
|
||||
Background="{DynamicResource AppAccentBrush}"
|
||||
Margin="0,2"
|
||||
IsVisible="{Binding $parent[ListBoxItem].IsSelected}" />
|
||||
<PathIcon Data="{StaticResource LockIcon}"
|
||||
Width="16" Height="16" />
|
||||
<TextBlock Text="{Binding NavDecrypt}"
|
||||
VerticalAlignment="Center" />
|
||||
</StackPanel>
|
||||
</ListBoxItem>
|
||||
<ListBoxItem>
|
||||
<StackPanel Orientation="Horizontal" Spacing="8">
|
||||
<Border Width="3" CornerRadius="1.5"
|
||||
@@ -161,6 +172,9 @@
|
||||
<DataTemplate DataType="vm:AlbumDownloadViewModel">
|
||||
<pages:AlbumDownloadPage />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="vm:DecryptViewModel">
|
||||
<pages:DecryptPage />
|
||||
</DataTemplate>
|
||||
<DataTemplate DataType="vm:SettingsViewModel">
|
||||
<pages:SettingsPage />
|
||||
</DataTemplate>
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
using Avalonia.Controls;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZonyLrcTools.Desktop.ViewModels;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Views;
|
||||
|
||||
@@ -10,29 +8,4 @@ public partial class MainWindow : Window
|
||||
{
|
||||
InitializeComponent();
|
||||
}
|
||||
|
||||
private void OnNavigationSelectionChanged(object? sender, SelectionChangedEventArgs e)
|
||||
{
|
||||
if (DataContext is not MainWindowViewModel viewModel) return;
|
||||
if (sender is not ListBox listBox) return;
|
||||
|
||||
var services = App.Services;
|
||||
if (services == null) return;
|
||||
|
||||
switch (listBox.SelectedIndex)
|
||||
{
|
||||
case 0:
|
||||
viewModel.CurrentPage = services.GetRequiredService<HomeViewModel>();
|
||||
break;
|
||||
case 1:
|
||||
viewModel.CurrentPage = services.GetRequiredService<LyricsDownloadViewModel>();
|
||||
break;
|
||||
case 2:
|
||||
viewModel.CurrentPage = services.GetRequiredService<AlbumDownloadViewModel>();
|
||||
break;
|
||||
case 3:
|
||||
viewModel.CurrentPage = services.GetRequiredService<SettingsViewModel>();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user