jeudi 18 octobre 2018

General purpose ViewModel class

My objective is to make a ViewModel class that takes any type of object and breaks it out into an ObservableCollection of its fields that can be displayed and modified in a View. I'm imagining the fields being wrapped in a FieldViewModel that exposes a 'string FieldName' property, as well as an 'object Value' property and maybe the Type.

class ViewModel : ViewModelBase
{
    public ViewModel(ref object instance)
    {
        foreach (var field in instance.GetType().GetFields())
        {
            Fields.Add(new FieldViewModel(instance, field));
        }
    }

    private ObservableCollection<FieldViewModel> _fields = new ObservableCollection<FieldViewModel>();
    public ObservableCollection<FieldViewModel> Fields
    {
        get { return _fields; }
        set
        {
            _fields = value;
            OnPropertyChanged();
        }
    }
}

The above pseudo-code is an attempt to try communicating my intention. Of course more code would be needed to determine if fields are read-only. If this is not possible, how would you recommend doing this? Please advise.

NOTE: my particular application only cares about fields, as opposed to properties. I did not create the data Models that I will be displaying in the UI.





Aucun commentaire:

Enregistrer un commentaire