Blazor Grid Bound Column by Field Name

前端 未结 1 446
死守一世寂寞
死守一世寂寞 2020-12-19 15:44

I\'m studying some paid grid components and they have a pretty cool \"Bound Column\" technique:


    
           


        
1条回答
  •  不知归路
    2020-12-19 16:17

    It's not a trivial solution, you should to understand how Blazor works with components. Basically, the way, is to register children MyColumn "templates" on outer MyGrid component, then, render grid dynamically with a bit of reflection. Below I post the recipe ready for copy-paste, test and learn.

    Step 0: Create the templated blazor demo:

    dotnet new blazorserver
    

    Step 1: Create Pages/MyColumn.razor component:

    @code {
        [Parameter]
        public string Field { get; set; }
    
        [CascadingParameter]
        private MyGrid Parent { get; set; }    
    
        protected override void OnInitialized()
        {
            base.OnInitialized();        
            Parent.AddColumn(this); //register child into parent
        }
    }
    

    Step 2: Create Pages/MyGrid.razor component:

    
    
            @ChildContent
            @foreach (var item in DataSource)
            {
                @RowItem(item) 
            }
        
    @code { [Parameter] public RenderFragment ChildContent { get; set; } [Parameter] public IEnumerable DataSource { get; set; } List Columns = new List(); public void AddColumn(MyColumn column) { Columns.Add(column); StateHasChanged(); }

    // Here the function to create each row dynamically:

        private RenderFragment RowItem(object row)
        {   
            int i = 0;
            return b =>          // create dynamically
            {
                b.OpenElement(++i, "tr");
                foreach(var column in Columns)
                {
                    b.OpenElement(++i, "td");
                    var val = row.GetType().GetProperty(column.Field)
                              .GetValue(row, null).ToString();                
                    b.AddContent(++i,val);
                    b.CloseElement();
                }
                b.CloseElement();
            };
        }
    }
    

    Step 3: Use your grid on Pages/FetchData.razor

    @page "/fetchdata"
    
    @using s.Data
    @inject WeatherForecastService ForecastService
    
    

    Weather forecast

    This component demonstrates fetching data from a service.

    @if (forecasts == null) {

    Loading...

    } else { } @code { private WeatherForecast[] forecasts; protected override async Task OnInitializedAsync() { forecasts = await ForecastService.GetForecastAsync(DateTime.Now); } }

    Result:

    0 讨论(0)
    提交回复
    热议问题