laatzen/Common/Ui/Common.UI/ViewModels/ManualProgrammingVM.cs
2025-06-06 16:12:39 +02:00

114 lines
3.5 KiB
C#

namespace Common.UI.ViewModels
{
using Common.Hardware.WaterMeter.eRegister.Features;
using Common.Hardware.WaterMeter.eRegister.Models;
using Common.UI.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
public class ManualProgrammingVM : VM<ManualProgrammingVM>
{
public ManualProgrammingVM()
{
var efeatures = new EregisterFeatures();
var dynamicFeatures = new DynamicTypeVM(efeatures);
var properties = dynamicFeatures
.GetAllProperties()
.ToList();
}
}
public class DynamicPropertyVM : VM<DynamicPropertyVM>
{
protected readonly Dictionary<string, DynamicPropertyVM> properties;
protected readonly PropertyInfo propertyInfo;
protected readonly object instance;
protected readonly object value;
public DynamicPropertyVM(object instance, PropertyInfo propertyInfo)
{
this.properties = new Dictionary<string, DynamicPropertyVM>();
this.propertyInfo = propertyInfo;
this.instance = instance;
if (this.propertyInfo != null)
{
this.Name = this.propertyInfo.Name;
this.value = Activator.CreateInstance(this.propertyInfo.PropertyType);
if (this.value is Pam pam)
{
this.Name = $"{pam.CmdHex} - {this.Name}";
}
}
}
public event Action PropertyValueChanged;
public string Name { get; }
private bool selected;
public bool Selected
{
get => this.selected;
set => this.SetValue(x =>
{
x.selected = value;
var propertyValue = default(object);
if (x.selected)
{
propertyValue = this.value;
}
this.propertyInfo.SetValue(this.instance, propertyValue);
this.PropertyValueChanged?.Invoke();
});
}
public virtual IEnumerable<DynamicPropertyVM> GetAllProperties()
=> this.properties
.Values
.SelectMany(x => x.GetAllProperties())
.Union(this.properties.Values)
.OrderBy(x => x.Name);
}
public class DynamicTypeVM : DynamicPropertyVM
{
private readonly Type type;
public DynamicTypeVM(object instance) : base(instance, null)
{
this.type = this.instance.GetType();
foreach (var propertyInfo in this.type.GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
var pamAttribute = propertyInfo.GetCustomAttribute<PamAttribute>();
if (pamAttribute is null)
{
continue;
}
var dynamicProperty = new DynamicPropertyVM(this.instance, propertyInfo);
if (propertyInfo.PropertyType == typeof(EregisterDebugFeatures))
{
var propertyInstance = new EregisterDebugFeatures();
propertyInfo.SetValue(this.instance, propertyInstance);
dynamicProperty = new DynamicTypeVM(propertyInstance);
}
this.properties[propertyInfo.Name] = dynamicProperty;
}
}
}
}