AyCode.Blazor/AyCode.Blazor.Components/Components/Grids/MgGridDataColumn.cs

94 lines
2.9 KiB
C#

using DevExpress.Blazor;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Rendering;
using System.Text.RegularExpressions;
namespace AyCode.Blazor.Components.Components.Grids;
/// <summary>
/// Extended DxGridDataColumn with additional parameters for InfoPanel support.
/// </summary>
public class MgGridDataColumn : DxGridDataColumn
{
private string? _urlLink;
private bool _isInitialized;
/// <summary>
/// Whether this column should be visible in the InfoPanel. Default is true.
/// </summary>
[Parameter]
public bool ShowInInfoPanel { get; set; } = true;
/// <summary>
/// Custom display format for InfoPanel (overrides DisplayFormat if set).
/// </summary>
[Parameter]
public string? InfoPanelDisplayFormat { get; set; }
/// <summary>
/// Column order in InfoPanel (lower = earlier). Default is int.MaxValue.
/// </summary>
[Parameter]
public int InfoPanelOrder { get; set; } = int.MaxValue;
/// <summary>
/// URL template with {property} placeholders that will be replaced with row values.
/// Example: https://shop.fruitbank.hu/Admin/Order/Edit/{Id}/{OrderId}
/// </summary>
[Parameter]
public string? UrlLink
{
get => _urlLink;
set
{
if (_urlLink == value) return;
_urlLink = value;
if (_isInitialized) UpdateCellDisplayTemplate();
}
}
protected override void OnParametersSet()
{
base.OnParametersSet();
_isInitialized = true;
UpdateCellDisplayTemplate();
}
private void UpdateCellDisplayTemplate()
{
if (!string.IsNullOrWhiteSpace(_urlLink))
{
CellDisplayTemplate = context => builder =>
{
var url = BuildUrlFromTemplate(_urlLink, context.DataItem);
builder.OpenElement(0, "a");
builder.AddAttribute(1, "href", url);
builder.AddAttribute(2, "target", "_blank");
builder.AddAttribute(3, "style", "text-decoration: none;");
builder.AddContent(4, context.DisplayText);
builder.CloseElement();
};
}
}
/// <summary>
/// Replaces {property} placeholders in the template with values from the data item.
/// Exposed for unit testing.
/// </summary>
internal static string BuildUrlFromTemplate(string template, object? dataItem)
{
if (dataItem == null) return template;
return Regex.Replace(template, "{([^}]+)}", match =>
{
var propName = match.Groups[1].Value;
var prop = dataItem.GetType().GetProperty(propName);
if (prop != null)
{
var value = prop.GetValue(dataItem);
return value?.ToString() ?? string.Empty;
}
return match.Value;
});
}
}