如何在blazor中动态显示图像标签?

时间:2019-12-14 17:18:06

标签: blazor blazor-server-side

我的页面上有一个可排序的表。

在表标题列中,我有:

<div>Inv. # @SortGlyph("inventory_number")</div>

在代码块中我有

    public string SortGlyph(string field)
    {
        if (field == _orderBy)
        {
            return _direction == "asc" ? "<img src='/images/uparrow.gif'>" : "<img src='/images/downarrow.gif'>";
        }
        return "";
    }

我认为我需要使用RenderFragment来完成此操作,但是我在弄清楚如何开始时遇到了麻烦。

2 个答案:

答案 0 :(得分:1)

直接回答:

这是Blazor的方式:

<div>Inv. # 
     @if IsSortedUpBy("inventory_number") {
        <img src='/images/uparrow.gif'>
     } 
     else if IsSortedDownBy("inventory_number") {
        <img src='/images/downarrow.gif'>
     }
</div>

代码:

public bool IsSortedUpBy(string field) => field == _orderBy && _direction == "asc";
public bool IsSortedUpBy(string field) => field == _orderBy && _direction != "asc";

奖金跟踪:

请记住,您可以使用parms将行为封装在own Blazor component中:

    <arrowdiv 
        label="Inv. # "
        state="@GetArrowStateForField(inventory_number)">
    </arrowdiv>

答案 1 :(得分:0)

在此示例中我省略了Field,因为我不确定组件的其余部分是如何实现的。我还认为您可能需要一次按多个字段进行排序。因此,为使答案简单起见,我缩小了实际问题:“如何动态显示图像标签?”。

要动态显示任何内容,只需将其包装在if语句中即可。要切换图像,您实际上可以交换一部分字符串,而不是替换整个<img元素。

在下面的示例中,如果未设置SortDirection,则由于if语句而不会显示。否则,将根据三元运算符的“方向”属性显示图像并显示正确的图像。

@if (!String.IsNullOrEmpty(SortDirection))
{
    <img src='/images/@(Direction).gif'>
}

@code {
    string Direction => SortDirection == "asc" ? "uparrow" : "downarrow";
    [Parameter] public string SortDirection { get; set; }
}
相关问题