Динамические компоненты для BlazorC#

Место общения программистов C#
Ответить
Anonymous
 Динамические компоненты для Blazor

Сообщение Anonymous »

Я создал этот универсальный компонент, чтобы иметь возможность передавать шаблон для представления списка или сетки
@*
Инструкции по использованию:

Код: Выделить всё

    The DynamicProductDisplay dynamically displays items in either a grid or list layout, depending on the user's selection.
Pass a list of items to the `Items` parameter.  Use the `GridViewTemplate` and `ListViewTemplate` parameters to specify
how each item should be rendered in grid or list view respectively.

To use DynamicProductDisplay with `GridProduct` and `ListedProduct`, define render fragments like this:

 AddToCart(product)"
OnAddToFavorites="() => AddToFavorites(product)" />"
ListViewTemplate="product => @"
GridColumnClass="col-md-4"
ListColumnClass="col-12" />

Replace `AddToCart` and `AddToFavorites` with your own event handlers.

Parameters:
- `Items`: The list of items to display.
- `GridViewTemplate`: Render fragment defining how each item is rendered in grid view.
- `ListViewTemplate`: Render fragment defining how each item is rendered in list view.
- `GridColumnClass`: CSS class for grid layout columns.
- `ListColumnClass`: CSS class for list layout columns.
*@

@typeparam TItem



@if (Items != null)
{
@foreach (var item in Items!)
{

@if (isGridView)
{
@GridViewTemplate(item);
}
else
{
@ListViewTemplate(item);
}

}
}


@code {
[Parameter] public List? Items { get; set; }

[Parameter] public bool isGridView { get; set; } = true;

[Parameter] public RenderFragment? GridViewTemplate { get; set; }
[Parameter] public RenderFragment? ListViewTemplate { get; set; }

[Parameter] public string GridColumnClass { get; set; } = "col-md-4";
[Parameter] public string ListColumnClass { get; set; } = "col-12";

private string gridOrListClass => isGridView ? GridColumnClass : ListColumnClass;
private string buttonTitle => isGridView ? "List View" : "Grid View";
}
мои шаблоны выглядят так:
grid->

Код: Выделить всё

@typeparam TItem
@inherits ComponentBase

@* Summary of Usage:
To use the GridProduct component, pass in the product's Name, ImageSource, Description, and Price as parameters.
Optionally, set MaxDescriptionLength to control the displayed length of the Description.
Provide EventCallback handlers for OnAddToCart and OnAddToFavorites to handle button clicks.

Example usage:


*@







@Name



@DescriptionSubstring




@Price.ToString("C")






Add to Cart


Add to Favorites




@code {
[Parameter] public string Name { get; set; } = string.Empty;
[Parameter] public string ImageSource { get; set; } = string.Empty;
[Parameter] public string Description { get; set; } = string.Empty;
[Parameter] public decimal Price { get; set; }
[Parameter] public int MaxDescriptionLength { get; set; } = 100;
[Parameter] public EventCallback OnAddToCart { get; set; }
[Parameter] public EventCallback OnAddToFavorites { get; set; }

private string DescriptionSubstring => Description.Length > MaxDescriptionLength
? $"{Description.Substring(0, MaxDescriptionLength)}..."
: Description;

private Task AddToCart() => OnAddToCart.InvokeAsync(null);
private Task AddToFavorites() => OnAddToFavorites.InvokeAsync(null);
}
список>

Код: Выделить всё

@* Summary of Usage:
To use the ListedProduct component, pass in the product's Name, ImageSource, Description, and Price as parameters.
Optionally, set MaxDescriptionLength to control the displayed length of the Description.
Provide EventCallback handlers for OnAddToCart and OnAddToFavorites to handle button clicks.

Example usage:


*@

@typeparam TItem
@inherits ComponentBase











@Name



@DescriptionSubstring




@Price.ToString("C")



Add to Cart
Add to Favorites




@code {
/// 
///
/// 
[Parameter] public string Name { get; set; } = string.Empty;
[Parameter] public string ImageSource { get; set; } = string.Empty;
[Parameter] public string Description { get; set; } = string.Empty;
[Parameter] public decimal Price { get; set; }
[Parameter] public int MaxDescriptionLength { get; set; } = 100;
[Parameter] public EventCallback OnAddToCart { get; set; }
[Parameter] public EventCallback OnAddToFavorites { get; set; }

private string DescriptionSubstring => Description.Length > MaxDescriptionLength ? $"{Description.Substring(0, MaxDescriptionLength)}..." : Description;

private Task AddToCart() => OnAddToCart.InvokeAsync(null);
private Task AddToFavorites() => OnAddToFavorites.InvokeAsync(null);

}
Я просто не могу заставить его работать.
Это мой подход неправильный или я что-то упускаю?
Я представлял, что делаю что-то вроде этого:

Код: Выделить всё

@page "/products-display"
@aBunchOfUsings



@code {
}
Вся суть в том, что я хочу, чтобы компоненты были универсальными и не зависели от типа для повторного использования. Либо я испортил синтаксис при использовании компонентов, либо что-то еще, я новичок в программировании, поэтому не бойтесь ничего исправлять.

Подробнее здесь: https://stackoverflow.com/questions/792 ... for-blazor
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C#»