123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- using Avalonia;
- using Avalonia.Threading;
- using CommunityToolkit.Mvvm.ComponentModel;
- using EventBus;
- using Shaker.Models;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics.CodeAnalysis;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Runtime.CompilerServices;
- namespace ShakerApp.ViewModels;
- public abstract class ViewModelBase<TModel>:ViewModelBase where TModel:IModel
- {
- public ViewModelBase(TModel model) : this()
- {
- UpDateModel(model);
- }
- private List<FieldInfo> AllFields = new List<FieldInfo>();
- private List<(string, IReadOnlyList<string>)> AllProperties = new List<(string, IReadOnlyList<string>)>();
- public ViewModelBase()
- {
- if (typeof(TModel).IsAnsiClass && !typeof(TModel).IsAbstract)
- {
- Model = Activator.CreateInstance<TModel>();
- AllFields = typeof(TModel).GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).ToList();
- this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
- .Where(x => x.GetCustomAttribute<ViewModels.PropertyAssociationAttribute>() != null)
- .ToList()
- .ForEach(x =>
- {
- var att = x.GetCustomAttribute<PropertyAssociationAttribute>();
- if (att == null || att.Names.Count == 0) return;
- AllProperties.Add((x.Name, att.Names));
- });
- }
- }
- [AllowNull]
- private TModel model = default;
- public virtual TModel Model { get => model; set => SetProperty(ref model, value); }
- public virtual void ReceiveServiceModel(TModel model)
- {
- if (typeof(TModel).IsAbstract || typeof(TModel).IsInterface) return;
- if (lastModel != null)
- {
- lastModel = (TModel)model.Clone();
- }
- UpDateModel(model);
- }
- public virtual void UpDateModel(TModel model)
- {
- if (typeof(TModel).IsAbstract || typeof(TModel).IsInterface) return;
- List<string> changedNames = new List<string>();
- if (model == null || AllFields.Count == 0) return;
- if (Model == null)
- {
- changedNames = AllFields.Select(x => x.Name).ToList();
- }
- else
- {
- AllFields.ForEach(x =>
- {
- var lastvalue = x.GetValue(Model);
- var fieldvalue = x.GetValue(model);
- if (!Object.Equals(lastvalue, fieldvalue))
- {
- changedNames.Add(x.Name);
- }
- });
- }
- Model = model;
- if (changedNames.Count == 0) return;
- List<string> nochanged = new List<string>();
- changedNames.ForEach(x =>
- {
- bool state = false;
- AllProperties.ForEach(y =>
- {
- if (y.Item2.Contains(x))
- {
- OnPropertyChanged(y.Item1);
- state = true;
- }
- });
- if (!state) nochanged.Add(x);
- });
- if (nochanged.Count == 0) return;
- RefreshUI(nochanged);
- }
- public virtual void Init()
- {
- }
- [AllowNull]
- private protected TModel lastModel;
- protected virtual void RefreshUI(List<string> changedNames)
- {
- }
- }
|