Files

95 lines
2.8 KiB
C#

using System;
using System.Collections.ObjectModel;
using System.Linq;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using GazpromApp.Messages;
using GazpromApp.Models;
namespace GazpromApp.ViewModels;
public partial class PropertyViewModel : ViewModelBase
{
public ViewModelBase? Parent { get; init; }
private Property Property { get; }
[ObservableProperty]
private string _name;
[ObservableProperty]
private string _value;
[ObservableProperty]
private DateTime _creationDate;
public ObservableCollection<PropertyViewModel> Properties { get; set; }
// Visual and other properties
[ObservableProperty]
private bool _isEditing;
[RelayCommand]
private void AddProperty() => Properties.Add(new PropertyViewModel() {Parent = this});
[RelayCommand]
private void RemoveProperty() => WeakReferenceMessenger.Default.Send(new RemovePropertyMessage(this));
[RelayCommand]
private void EditProperty() => IsEditing = !IsEditing;
private void RemoveProperty(object sender, RemovePropertyMessage msg)
{
if (Properties.Contains(msg.Property))
Properties.Remove(msg.Property);
}
public Property GetProperty(Property? parent = null)
{
Property.Name = Name;
Property.Value = Value;
Property.CreationDate = CreationDate;
Property.Parent = parent;
Property.Properties = Properties.Select(e => e.GetProperty(Property)).ToList();
return Property;
}
public PropertyViewModel()
{
Name = "Имя свойства";
Value = "Значение свойства";
CreationDate = DateTime.Now;
Properties = [];
Parent = null;
Property = new Property();
WeakReferenceMessenger.Default.Register<RemovePropertyMessage>(this, RemoveProperty);
}
public PropertyViewModel(Property property, PropertyViewModel? parent = null)
{
Name = property.Name;
Value = property.Value;
CreationDate = property.CreationDate;
Properties = new ObservableCollection<PropertyViewModel>(
property.Properties.Select(e => new PropertyViewModel(e, this)));
Parent = property.Parent is null ? null : parent;
Property = property;
WeakReferenceMessenger.Default.Register<RemovePropertyMessage>(this, RemoveProperty);
}
public PropertyViewModel(PropertyViewModel property)
{
Name = "Имя свойства";
Value = "Значение свойства";
Properties = [];
Parent = property;
Property = new Property();
WeakReferenceMessenger.Default.Register<RemovePropertyMessage>(this, RemoveProperty);
}
}