public void DynamicFill(IEnumerable <IFormTreeNode> nodes, IPropertyValueConverter converter) { var objectPopulator = new ObjectPopulator(converter); foreach (var node in nodes) { var propValue = (TKey)converter.ConvertToPropertyType(typeof(TKey), node.Key); TElement element; if (elements == null || !HasKey(propValue)) { element = Activator.CreateInstance <TElement>(); Add(element); var fieldName = MemberHelpers.GetKeyPropertyFieldName <TElement>(); var(field, typeOfField) = MemberHelpers.GetPropertyField(element, fieldName); // Convert property to field, for support readonly model object fieldValue = converter.ConvertToFieldType(typeOfField, propValue); element.SetValue(field, fieldValue); } else { element = this[propValue]; } if (node is FormTreeCollection formTreeCollection) { objectPopulator.Populate(formTreeCollection.Childs, element); } else { throw new NotSupportedException(); } } }
/// <summary> /// Gets the value associated with the specified key. /// </summary> /// <param name="key">The key of the value to get.</param> /// <returns> The value associated with the specified key. If the specified key is not found, /// a get operation throws a System.Collections.Generic.KeyNotFoundException, and /// a set operation creates a new element with the specified key.</returns> public TElement this[TKey key] { get { var fieldName = MemberHelpers.GetKeyPropertyFieldName <TElement>(); return(elements.First(x => Equals(x.GetValue <TKey>(fieldName), key))); } }
/// <summary> /// Check present key in elements. /// </summary> /// <param name="key">Search key.</param> /// <returns></returns> public bool HasKey(TKey key) { var fieldName = MemberHelpers.GetKeyPropertyFieldName <TElement>(); return(HasKey(key, fieldName)); }