跨平台WPF音乐商店应用程序

目录

一 简介

二 设计思路

三 源码


一 简介

支持在线检索音乐,支持实时浏览当前收藏的音乐及音乐数据的持久化。

二 设计思路

采用MVVM架构,前后端分离,子界面弹出始终位于主界面的中心。

三 源码

视窗引导启动源码:

namespace Avalonia.MusicStore
{public class ViewLocator : IDataTemplate{public Control? Build(object? data){if (data is null)return null;var name = data.GetType().FullName!.Replace("ViewModel", "View", StringComparison.Ordinal);var type = Type.GetType(name);if (type != null){var control = (Control)Activator.CreateInstance(type)!;control.DataContext = data;return control;}return new TextBlock { Text = "Not Found: " + name };}public bool Match(object? data){return data is ViewModelBase;}}
}using Avalonia;
using Avalonia.ReactiveUI;
using System;namespace Avalonia.MusicStore
{internal sealed class Program{// Initialization code. Don't use any Avalonia, third-party APIs or any// SynchronizationContext-reliant code before AppMain is called: things aren't initialized// yet and stuff might break.[STAThread]public static void Main(string[] args) => BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);// Avalonia configuration, don't remove; also used by visual designer.public static AppBuilder BuildAvaloniaApp()=> AppBuilder.Configure<App>().UsePlatformDetect().WithInterFont().LogToTrace().UseReactiveUI();}
}

模型源码:

using iTunesSearch.Library;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;namespace Avalonia.MusicStore.Models
{public class Album{private static iTunesSearchManager s_SearchManager = new();public string Artist { get; set; }public string Title { get; set; }public string CoverUrl { get; set; }public Album(string artist, string title, string coverUrl){Artist = artist;Title = title;CoverUrl = coverUrl;}public static async Task<IEnumerable<Album>> SearchAsync(string searchTerm){var query = await s_SearchManager.GetAlbumsAsync(searchTerm).ConfigureAwait(false);return query.Albums.Select(x =>new Album(x.ArtistName, x.CollectionName,x.ArtworkUrl100.Replace("100x100bb", "600x600bb")));}private static HttpClient s_httpClient = new();private string CachePath => $"./Cache/{Artist} - {Title}";public async Task<Stream> LoadCoverBitmapAsync(){if (File.Exists(CachePath + ".bmp")){return File.OpenRead(CachePath + ".bmp");}else{var data = await s_httpClient.GetByteArrayAsync(CoverUrl);return new MemoryStream(data);}}public async Task SaveAsync(){if (!Directory.Exists("./Cache")){Directory.CreateDirectory("./Cache");}using (var fs = File.OpenWrite(CachePath)){await SaveToStreamAsync(this, fs);}}public Stream SaveCoverBitmapStream(){return File.OpenWrite(CachePath + ".bmp");}private static async Task SaveToStreamAsync(Album data, Stream stream){await JsonSerializer.SerializeAsync(stream, data).ConfigureAwait(false);}public static async Task<Album> LoadFromStream(Stream stream){return (await JsonSerializer.DeserializeAsync<Album>(stream).ConfigureAwait(false))!;}public static async Task<IEnumerable<Album>> LoadCachedAsync(){if (!Directory.Exists("./Cache")){Directory.CreateDirectory("./Cache");}var results = new List<Album>();foreach (var file in Directory.EnumerateFiles("./Cache")){if (!string.IsNullOrWhiteSpace(new DirectoryInfo(file).Extension)) continue;await using var fs = File.OpenRead(file);results.Add(await Album.LoadFromStream(fs).ConfigureAwait(false));}return results;}}
}

模型视图源码:

using Avalonia.Media.Imaging;
using Avalonia.MusicStore.Models;
using ReactiveUI;
using System.Threading.Tasks;namespace Avalonia.MusicStore.ViewModels
{public class AlbumViewModel : ViewModelBase{private readonly Album _album;public AlbumViewModel(Album album){_album = album;}public string Artist => _album.Artist;public string Title => _album.Title;private Bitmap? _cover;public Bitmap? Cover{get => _cover;private set => this.RaiseAndSetIfChanged(ref _cover, value);}public async Task LoadCover(){await using (var imageStream = await _album.LoadCoverBitmapAsync()){Cover = await Task.Run(() => Bitmap.DecodeToWidth(imageStream, 400));}}public async Task SaveToDiskAsync(){await _album.SaveAsync();if (Cover != null){var bitmap = Cover;await Task.Run(() =>{using (var fs = _album.SaveCoverBitmapStream()){bitmap.Save(fs);}});}}}
}
using Avalonia.MusicStore.Models;
using ReactiveUI;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
using System.Windows.Input;namespace Avalonia.MusicStore.ViewModels
{public class MainWindowViewModel : ViewModelBase{public ICommand BuyMusicCommand { get; }public Interaction<MusicStoreViewModel, AlbumViewModel?> ShowDialog { get; }public ObservableCollection<AlbumViewModel> Albums { get; } = new();public MainWindowViewModel(){ShowDialog = new Interaction<MusicStoreViewModel, AlbumViewModel?>();BuyMusicCommand = ReactiveCommand.CreateFromTask(async () =>{var store = new MusicStoreViewModel();var result = await ShowDialog.Handle(store);if (result != null){Albums.Add(result);await result.SaveToDiskAsync();}});RxApp.MainThreadScheduler.Schedule(LoadAlbums);}private async void LoadAlbums(){var albums = (await Album.LoadCachedAsync()).Select(x => new AlbumViewModel(x));foreach (var album in albums){Albums.Add(album);}foreach (var album in Albums.ToList()){await album.LoadCover();}}}
}
using Avalonia.MusicStore.Models;
using ReactiveUI;
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive;
using System.Reactive.Linq;
using System.Threading;namespace Avalonia.MusicStore.ViewModels
{public class MusicStoreViewModel : ViewModelBase{private string? _searchText;private bool _isBusy;public string? SearchText{get => _searchText;set => this.RaiseAndSetIfChanged(ref _searchText, value);}public bool IsBusy{get => _isBusy;set => this.RaiseAndSetIfChanged(ref _isBusy, value);}private AlbumViewModel? _selectedAlbum;public ObservableCollection<AlbumViewModel> SearchResults { get; } = new();public AlbumViewModel? SelectedAlbum{get => _selectedAlbum;set => this.RaiseAndSetIfChanged(ref _selectedAlbum, value);}public MusicStoreViewModel(){this.WhenAnyValue(x => x.SearchText).Throttle(TimeSpan.FromMilliseconds(400)).ObserveOn(RxApp.MainThreadScheduler).Subscribe(DoSearch!);BuyMusicCommand = ReactiveCommand.Create(() =>{return SelectedAlbum;});}private async void DoSearch(string s){IsBusy = true;SearchResults.Clear();_cancellationTokenSource?.Cancel();_cancellationTokenSource = new CancellationTokenSource();var cancellationToken = _cancellationTokenSource.Token;if (!string.IsNullOrWhiteSpace(s)){var albums = await Album.SearchAsync(s);foreach (var album in albums){var vm = new AlbumViewModel(album);SearchResults.Add(vm);}if (!cancellationToken.IsCancellationRequested){LoadCovers(cancellationToken);}}IsBusy = false;}private async void LoadCovers(CancellationToken cancellationToken){foreach (var album in SearchResults.ToList()){await album.LoadCover();if (cancellationToken.IsCancellationRequested){return;}}}private CancellationTokenSource? _cancellationTokenSource;public ReactiveCommand<Unit, AlbumViewModel?> BuyMusicCommand { get; }}
}
using ReactiveUI;namespace Avalonia.MusicStore.ViewModels
{public class ViewModelBase : ReactiveObject{}
}

视图源码:

<UserControlx:Class="Avalonia.MusicStore.Views.AlbumView"xmlns="https://github.com/avaloniaui"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:vm="using:Avalonia.MusicStore.ViewModels"Width="200"d:DesignHeight="450"d:DesignWidth="800"x:DataType="vm:AlbumViewModel"mc:Ignorable="d"><StackPanel Width="200" Spacing="5"><Border ClipToBounds="True" CornerRadius="10"><Panel Background="#7FFF22DD"><ImageWidth="200"Source="{Binding Cover}"Stretch="Uniform" /><Panel Height="200" IsVisible="{Binding Cover, Converter={x:Static ObjectConverters.IsNull}}"><PathIconWidth="75"Height="75"Data="{StaticResource music_regular}" /></Panel></Panel></Border><TextBlock HorizontalAlignment="Center" Text="{Binding Title}" /><TextBlock HorizontalAlignment="Center" Text="{Binding Artist}" /></StackPanel>
</UserControl>
<Windowx:Class="Avalonia.MusicStore.Views.MainWindow"xmlns="https://github.com/avaloniaui"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:views="clr-namespace:Avalonia.MusicStore.Views"xmlns:vm="using:Avalonia.MusicStore.ViewModels"Title="Avalonia.MusicStore"d:DesignHeight="450"d:DesignWidth="800"x:DataType="vm:MainWindowViewModel"Background="Transparent"ExtendClientAreaToDecorationsHint="True"Icon="/Assets/avalonia-logo.ico"TransparencyLevelHint="AcrylicBlur"WindowStartupLocation="CenterScreen"mc:Ignorable="d"><Panel><ExperimentalAcrylicBorder IsHitTestVisible="False"><ExperimentalAcrylicBorder.Material><ExperimentalAcrylicMaterialBackgroundSource="Digger"MaterialOpacity="0.65"TintColor="Black"TintOpacity="1" /></ExperimentalAcrylicBorder.Material></ExperimentalAcrylicBorder><Panel Margin="40"><ButtonHorizontalAlignment="Right"VerticalAlignment="Top"Command="{Binding BuyMusicCommand}"><PathIcon Data="{StaticResource store_microsoft_regular}" /></Button><ItemsControl Margin="0,40,0,0" ItemsSource="{Binding Albums}"><ItemsControl.ItemsPanel><ItemsPanelTemplate><WrapPanel /></ItemsPanelTemplate></ItemsControl.ItemsPanel><ItemsControl.ItemTemplate><DataTemplate><views:AlbumView Margin="0,0,20,20" /></DataTemplate></ItemsControl.ItemTemplate></ItemsControl></Panel></Panel></Window>
using Avalonia.MusicStore.ViewModels;
using Avalonia.ReactiveUI;
using ReactiveUI;
using System.Threading.Tasks;namespace Avalonia.MusicStore.Views
{public partial class MainWindow : ReactiveWindow<MainWindowViewModel>{public MainWindow(){InitializeComponent();this.WhenActivated(action => action(ViewModel!.ShowDialog.RegisterHandler(DoShowDialogAsync)));}private async Task DoShowDialogAsync(InteractionContext<MusicStoreViewModel,AlbumViewModel?> interaction){var dialog = new MusicStoreWindow();dialog.DataContext = interaction.Input;var result = await dialog.ShowDialog<AlbumViewModel?>(this);interaction.SetOutput(result);}}
}
<UserControlx:Class="Avalonia.MusicStore.Views.MusicStoreView"xmlns="https://github.com/avaloniaui"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:vm="using:Avalonia.MusicStore.ViewModels"d:DesignHeight="450"d:DesignWidth="800"x:DataType="vm:MusicStoreViewModel"mc:Ignorable="d"><DockPanel><StackPanel DockPanel.Dock="Top"><TextBox Text="{Binding SearchText}" Watermark="Search for Albums...." /><ProgressBar IsIndeterminate="True" IsVisible="{Binding IsBusy}" /></StackPanel><ButtonHorizontalAlignment="Center"Command="{Binding BuyMusicCommand}"Content="Buy Album"DockPanel.Dock="Bottom" /><ListBoxMargin="0,20"Background="Transparent"ItemsSource="{Binding SearchResults}"SelectedItem="{Binding SelectedAlbum}"><ListBox.ItemsPanel><ItemsPanelTemplate><WrapPanel /></ItemsPanelTemplate></ListBox.ItemsPanel></ListBox></DockPanel>
</UserControl>
<Windowx:Class="Avalonia.MusicStore.Views.MusicStoreWindow"xmlns="https://github.com/avaloniaui"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:views="using:Avalonia.MusicStore.Views"Title="MusicStoreWindow"Width="1000"Height="550"ExtendClientAreaToDecorationsHint="True"TransparencyLevelHint="AcrylicBlur"WindowStartupLocation="CenterOwner"mc:Ignorable="d"><Panel><ExperimentalAcrylicBorder IsHitTestVisible="False"><ExperimentalAcrylicBorder.Material><ExperimentalAcrylicMaterialBackgroundSource="Digger"MaterialOpacity="0.65"TintColor="Black"TintOpacity="1" /></ExperimentalAcrylicBorder.Material></ExperimentalAcrylicBorder><Panel Margin="40"><views:MusicStoreView /></Panel></Panel>
</Window>
using Avalonia.MusicStore.ViewModels;
using Avalonia.ReactiveUI;
using ReactiveUI;
using System;namespace Avalonia.MusicStore.Views
{public partial class MusicStoreWindow : ReactiveWindow<MusicStoreViewModel>{public MusicStoreWindow(){InitializeComponent();this.WhenActivated(action => action(ViewModel!.BuyMusicCommand.Subscribe(Close)));}}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://xiahunao.cn/news/3248009.html

如若内容造成侵权/违法违规/事实不符,请联系瞎胡闹网进行投诉反馈,一经查实,立即删除!

相关文章

【LLM大模型】介绍一个大语言模型的微调框架Swift

一、什么微调finetune 在大语言模型中&#xff0c;微调&#xff08;Fine-tuning&#xff09;是一种重要的技术&#xff0c;用于提升模型在特定任务或领域上的性能。微调&#xff08;Fine-tuning&#xff09;是指在已经预训练好的大语言模型基础上&#xff0c;使用特定领域或任…

【博士每天一篇文献-算法】连续学习算法之HNet:Continual learning with hypernetworks

阅读时间&#xff1a;2023-12-26 1 介绍 年份&#xff1a;2019 作者&#xff1a;Johannes von Oswald&#xff0c;Google Research&#xff1b;Christian Henning&#xff0c;EthonAI AG&#xff1b;Benjamin F. Grewe&#xff0c;苏黎世联邦理工学院神经信息学研究所 期刊&a…

镜像与容器

Docker Image (镜像) Docker 镜像概念 Docker iamge 本质上是一个 read-only 只读文件&#xff0c;这个文件包含了文件系统、源码、库文件、依赖、工具等一些运行 application 所必需的文件。 可以把 Docker image 理解成一个模板&#xff0c;可以通过这个模板实例化出来很多…

Qt类 | QLabel类详解

文章目录 一、QLabel类介绍二、Properties&#xff08;属性&#xff09;三、Public Functions&#xff08;公共函数&#xff09;1.构造函数2.alignment与setAlignment函数 -- 标签内容的对齐方式3.buddy与setBuddy函数 -- QLabel关联的伙伴控件4.hasScaledContents与setScaledC…

在学习使用LabVIEW的过程中,需要注意哪些问题?

在学习使用LabVIEW的过程中&#xff0c;需要注意以下问题&#xff1a; 1. 基础知识 图形化编程思维&#xff1a; LabVIEW采用图形化编程方式&#xff0c;与传统的文本编程语言有很大不同&#xff0c;需要适应这种新的编程思维方式。数据流概念&#xff1a; 理解LabVIEW的核心数…

Django Q()函数

Q() 函数的作用 在Django中&#xff0c;Q()函数是一个非常有用的工具&#xff0c;主要用于构建复杂的查询。它允许你创建复杂的查询语句&#xff0c;包括AND、OR和NOT逻辑操作。这对于处理复杂的数据库查询特别有用&#xff0c;特别是在你需要组合多个条件或处理复杂的过滤逻辑…

深入理解Android中的缓存与文件存储目录

&#x1f31f; 引言 在Android应用开发中&#xff0c;合理管理应用的数据存储至关重要。应用可能需要保存各种类型的数据&#xff0c;从简单的配置信息到多媒体文件&#xff0c;甚至是缓存数据以提高性能和用户体验。Android提供了多个内置目录来满足这些需求&#xff0c;但它…

唐山养老院哪家好---守护晚年幸福,用服务引领老年人高品质养老生活

随着社会的快速发展和人口老龄化趋势的加剧&#xff0c;老年人对养老机构的需求日益增长&#xff0c;选择养老机构作为养老方式已成为许多老年人的必然选择。随着年龄的增长&#xff0c;生理功能的退化和疾病风险的增加&#xff0c;使得老年人更加需要专业的医疗照护和日常生活…

《大数据基础》相关知识点及考点,例题

1.6大数据计算模式 1、MapReduce可以并行执行大规模数据处理任务&#xff0c;用于大规模数据集&#xff08;大于1TB&#xff09;的并行运算。MapReduce 极大地方便了分布式编程工作&#xff0c;它将复杂的、运行于大规模集群上的并行计算过程高度地抽象为两个函数一一Map和Redu…

nginx全局块的user指令

文章目录 1、user指令1.1、进入nginx解压的目录1.2、./configure --help1.3、工作进程默认是nobody 2、user指令的使用步骤:2.1、设置一个用户信息"www"2.2、 创建一个用户2.3、./nginx -s reload2.4、创建/root/html/index.html页面&#xff0c;添加如下内容2.5、修…

《电脑知识与技术》是什么级别的期刊?是正规期刊?能评职称吗?

​问题解答 问&#xff1a;《电脑知识与技术》是不是核心期刊&#xff1f; 答&#xff1a;不是&#xff0c;是知网收录的正规学术期刊。 问&#xff1a;《电脑知识与技术》级别&#xff1f; 答&#xff1a;省级。主管单位&#xff1a;安徽出版集团有限责任公司 主办单位&a…

海外营销推广:快速创建维基百科(wiki)词条-大舍传媒

一、维基百科的永久留存问题 许多企业和个人关心维基百科是否能永久留存。实际上&#xff0c;只要企业和个人的行为没有引起维基百科管理方的反感&#xff0c;词条就可以长期保存。如果有恶意行为或被投诉&#xff0c;维基百科可能会对词条进行删除或修改。 二、创建维基百科…

FPGA 实现DDR4的读写

1 硬件设计 FPGA 端&#xff1a; DDR4: 2 验证方案 3 仿真验证 4 DDR4 下板验证

【有效验证】解决SQLyog连接MYSQL的错误 1251 - Client does not support

目录 一、原因分析&#xff1a; 二、进入到mysql 三、查看当前加密方式 四、更改加密方式 五、查看是否成功 前言&#xff1a;使用一个开源软件使用sqlyog、navcat都报1251错误&#xff0c;网上都是提示升级客户端&#xff0c;还有一种就是修改mysql配置。本文就是修改配置…

QT实现图片开关控件-自定义控件

开关按钮大家应该很熟悉&#xff0c;在设置里面经常遇到&#xff0c;切换时候的滑动效果比较帅气。通常说的开关按钮&#xff0c;有两个状态&#xff1a;on、off。大部分的开关按钮控件&#xff0c;基本上有两大类&#xff0c;第一类是纯代码绘制&#xff0c;这种对代码的掌控度…

WEB前端06-BOM对象

BOM浏览器对象模型 浏览器对象模型&#xff1a;将浏览器的各个组成部分封装成对象。是用于描述浏览器中对象与对象之间层次关系的模型&#xff0c;提供了独立于页面内容、并能够与浏览器窗口进行交互的对象结构。 组成部分 Window&#xff1a;浏览器窗口对象 Navigator&…

PHP手边酒店多商户版平台小程序系统源码

&#x1f3e8;【旅行新宠】手边酒店多商户版小程序&#xff0c;一键解锁住宿新体验&#xff01;&#x1f6cc; &#x1f308;【开篇&#xff1a;旅行新伴侣&#xff0c;尽在掌握】&#x1f308; 还在为旅行中的住宿选择而纠结吗&#xff1f;是时候告别繁琐的搜索和比价过程&a…

Java反射机制基础知识赏析、接口、实现类、方法

前言 最近打算手写一个RPC&#xff0c;但奈何自己Java基础知识中的反射就很欠缺&#xff0c;第一章就看不太懂了&#xff0c;特地编写了几个小Demo验证一下Java中关于反射的基础知识。 目录组织结构 代码编写 // TestService接口 package reflect.testServices;import main.v…

基于asp.net 在线订票管理系统 设计与实现

博主介绍&#xff1a;专注于Java .net php phython 小程序 等诸多技术领域和毕业项目实战、企业信息化系统建设&#xff0c;从业十五余年开发设计教学工作 ☆☆☆ 精彩专栏推荐订阅☆☆☆☆☆不然下次找不到哟 我的博客空间发布了1000毕设题目 方便大家学习使用 感兴趣的可以…

Vue封装文件上传组件(支持图片、PDF、Excel、word预览下载)

一、准备工作 安装预览依赖包&#xff1a;exceljs、mammoth、vue-pdf 二、封装组件 文件上传组件 fileUploadPro.vue。默认预览、下载是true,可通过isPreView、isDownLoad控制 <template><div style"display: flex"><el-uploadmultipleaction&qu…