PrettyBlazor
PrettyBlazor copied to clipboard
Consider adding an Index to your Iterator
We started down the path of doing things like you are doing, but came up with a slightly different approach for the Iterator and Iterations... Essentially, we tried to keep as much of the razor tags as close to C# as possible. This implementation breaks one thing I like better about yours... and that is you have direct access to the object in the loop. With the below method,, one must understand you have an Item as well as an Index.
public class ComponentContext<T> where T : ComponentBase
{
public ComponentContext(T @component) => Component = @component;
public T Component { get; set; }
}
public class ForEach<T> : ComponentBase
{
[Parameter]
public IEnumerable<T> Items { get; set; }
[Parameter]
public RenderFragment<ForEachContext<T>> ChildContent { get; set; }
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
var index = 0;
foreach (var item in Items)
builder?.AddContent(0, ChildContent(new ForEachContext<T>(this, item, index++)));
}
}
public class ForEachContext<T> : ComponentContext<ForEach<T>>
{
public ForEachContext(ForEach<T> component, T item, int index) : base(component)
{
Item = item;
Index = index;
}
public T Item { get; }
public int Index { get; }
}
+1