Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions src/BootstrapBlazor.Server/Components/Samples/CheckboxLists.razor
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,19 @@
</ValidateForm>
</DemoBlock>

<DemoBlock Title="@Localizer["GenericTitle"]" Introduction="@Localizer["GenericIntro"]" Name="Generic">
<CheckboxListGeneric @bind-Value="@_selectedFoos" Items="@GenericItems" />
<section ignore>
@if (_selectedFoos != null)
{
foreach (var item in _selectedFoos)
{
<div>@item.Name</div>
}
}
</section>
</DemoBlock>

<AttributeTable Items="@GetAttributes()" />

<EventTable Items="@GetEvents()" />
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,11 @@ public partial class CheckboxLists
[NotNull]
private IEnumerable<SelectedItem>? Items5 { get; set; }

[NotNull]
private IEnumerable<SelectedItem<Foo>>? GenericItems { get; set; }

private List<Foo>? _selectedFoos;

/// <summary>
/// OnInitialized method
/// </summary>
Expand Down Expand Up @@ -89,6 +94,22 @@ protected override void OnInitialized()
FooItems = Foo.GenerateHobbies(LocalizerFoo);
}

/// <summary>
/// <inheritdoc/>
/// </summary>
/// <returns></returns>
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();

GenericItems = new List<SelectedItem<Foo>>()
{
new() { Text = Localizer["item1"], Value = new Foo() { Name = LocalizerFoo["Foo.Name", "001"] } },
new() { Text = Localizer["item2"], Value = new Foo() { Name = LocalizerFoo["Foo.Name", "002"] } },
new() { Text = Localizer["item3"], Value = new Foo() { Name = LocalizerFoo["Foo.Name", "003"] } },
};
}

[NotNull]
private Foo? Model { get; set; }

Expand Down
2 changes: 1 addition & 1 deletion src/BootstrapBlazor/Components/Checkbox/CheckboxList.razor
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ else
<div @attributes="@AdditionalAttributes" id="@Id" class="@ClassString" tabindex="0" hidefocus="true">
@foreach (var item in Items)
{
<div class="@CheckboxItemClassString">
<div @key="item" class="@CheckboxItemClassString">
<Checkbox TValue="bool" IsDisabled="GetDisabledState(item)"
ShowAfterLabel="true" ShowLabel="false" ShowLabelTooltip="ShowLabelTooltip"
DisplayText="@item.Text" OnBeforeStateChanged="_onBeforeStateChangedCallback!"
Expand Down
36 changes: 36 additions & 0 deletions src/BootstrapBlazor/Components/Checkbox/CheckboxListGeneric.razor
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
@namespace BootstrapBlazor.Components
@typeparam TValue
@inherits ValidateBase<List<TValue>>

@if (IsShowLabel)
{
<BootstrapLabel required="@Required" for="@Id" ShowLabelTooltip="ShowLabelTooltip" Value="@DisplayText" />
}

@if (IsButton)
{
<div @attributes="@AdditionalAttributes" class="@ButtonClassString">
<div class="@ButtonGroupClassString" role="group">
@foreach (var item in Items)
{
<DynamicElement TagName="span" TriggerClick="!IsDisabled" OnClick="() => OnClick(item)" class="@GetButtonItemClassString(item)">
@item.Text
</DynamicElement>
}
</div>
</div>
}
else
{
<div @attributes="@AdditionalAttributes" id="@Id" class="@ClassString" tabindex="0" hidefocus="true">
@foreach (var item in Items)
{
<div @key="item" class="@CheckboxItemClassString">
<Checkbox TValue="bool" IsDisabled="GetDisabledState(item)"
ShowAfterLabel="true" ShowLabel="false" ShowLabelTooltip="ShowLabelTooltip"
DisplayText="@item.Text" OnBeforeStateChanged="_onBeforeStateChangedCallback!"
Value="@item.Active" OnStateChanged="@((state, v) => OnStateChanged(item, v))"></Checkbox>
</div>
}
</div>
}
244 changes: 244 additions & 0 deletions src/BootstrapBlazor/Components/Checkbox/CheckboxListGeneric.razor.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License
// See the LICENSE file in the project root for more information.
// Maintainer: Argo Zhang([email protected]) Website: https://www.blazor.zone

using Microsoft.Extensions.Localization;
using System.Reflection;

namespace BootstrapBlazor.Components;

/// <summary>
/// CheckboxList 组件基类
/// </summary>
public partial class CheckboxListGeneric<TValue> : IModelEqualityComparer<TValue>
{
/// <summary>
/// 获得 组件样式
/// </summary>
private string? ClassString => CssBuilder.Default("checkbox-list form-control")
.AddClass("no-border", !ShowBorder && ValidCss != "is-invalid")
.AddClass("is-vertical", IsVertical)
.AddClass(CssClass).AddClass(ValidCss)
.Build();

/// <summary>
/// 获得 组件内部 Checkbox 项目样式
/// </summary>
protected string? CheckboxItemClassString => CssBuilder.Default("checkbox-item")
.AddClass(CheckboxItemClass)
.Build();

private string? ButtonClassString => CssBuilder.Default("checkbox-list is-button")
.AddClassFromAttributes(AdditionalAttributes)
.Build();

private string? ButtonGroupClassString => CssBuilder.Default("btn-group")
.AddClass("disabled", IsDisabled)
.AddClass("btn-group-vertical", IsVertical)
.Build();

private string? GetButtonItemClassString(SelectedItem<TValue> item) => CssBuilder.Default("btn")
.AddClass($"active bg-{Color.ToDescriptionString()}", IsEquals(item.Value))
.Build();

/// <summary>
/// 获得/设置 数据主键标识标签 默认为 <see cref="KeyAttribute"/><code><br /></code>用于判断数据主键标签,如果模型未设置主键时可使用 <see cref="ModelEqualityComparer"/> 参数自定义判断 <code><br /></code>数据模型支持联合主键
/// </summary>
[Parameter]
[NotNull]
public Type? CustomKeyAttribute { get; set; } = typeof(KeyAttribute);

/// <summary>
/// 获得/设置 比较数据是否相同回调方法 默认为 null
/// <para>提供此回调方法时忽略 <see cref="CustomKeyAttribute"/> 属性</para>
/// </summary>
[Parameter]
public Func<TValue, TValue, bool>? ModelEqualityComparer { get; set; }

/// <summary>
/// 获得/设置 数据源
/// </summary>
[Parameter]
[NotNull]
public IEnumerable<SelectedItem<TValue>>? Items { get; set; }

/// <summary>
/// 获得/设置 是否为按钮样式 默认 false
/// </summary>
[Parameter]
public bool IsButton { get; set; }

/// <summary>
/// 获得/设置 Checkbox 组件布局样式
/// </summary>
[Parameter]
public string? CheckboxItemClass { get; set; }

/// <summary>
/// 获得/设置 是否显示边框 默认为 true
/// </summary>
[Parameter]
public bool ShowBorder { get; set; } = true;

/// <summary>
/// 获得/设置 是否为竖向排列 默认为 false
/// </summary>
[Parameter]
public bool IsVertical { get; set; }

/// <summary>
/// 获得/设置 按钮颜色 默认为 None 未设置
/// </summary>
[Parameter]
public Color Color { get; set; }

/// <summary>
/// 获得/设置 SelectedItemChanged 方法
/// </summary>
[Parameter]
public Func<IEnumerable<SelectedItem<TValue>>, List<TValue>, Task>? OnSelectedChanged { get; set; }

/// <summary>
/// 获得/设置 最多选中数量
/// </summary>
[Parameter]
public int MaxSelectedCount { get; set; }

/// <summary>
/// 获得/设置 超过最大选中数量时回调委托
/// </summary>
[Parameter]
public Func<Task>? OnMaxSelectedCountExceed { get; set; }

[Inject]
[NotNull]
private IStringLocalizerFactory? LocalizerFactory { get; set; }

/// <summary>
/// 获得 当前选项是否被禁用
/// </summary>
/// <param name="item"></param>
/// <returns></returns>
protected bool GetDisabledState(SelectedItem<TValue> item) => IsDisabled || item.IsDisabled;

private Func<CheckboxState, Task<bool>>? _onBeforeStateChangedCallback;

/// <summary>
/// OnInitialized 方法
/// </summary>
protected override void OnInitialized()
{
base.OnInitialized();

// 处理 Required 标签
if (EditContext != null && FieldIdentifier != null)
{
var pi = FieldIdentifier.Value.Model.GetType().GetPropertyByName(FieldIdentifier.Value.FieldName);
if (pi != null)
{
var required = pi.GetCustomAttribute<RequiredAttribute>(true);
if (required != null)
{
Rules.Add(new RequiredValidator()
{
LocalizerFactory = LocalizerFactory,
ErrorMessage = required.ErrorMessage,
AllowEmptyString = required.AllowEmptyStrings
});
}
}
}
}

/// <summary>
/// OnParametersSet 方法
/// </summary>
protected override void OnParametersSet()
{
base.OnParametersSet();

if (IsButton && Color == Color.None)
{
Color = Color.Primary;
}

Items ??= [];

_onBeforeStateChangedCallback = MaxSelectedCount > 0 ? new Func<CheckboxState, Task<bool>>(OnBeforeStateChanged) : null;

// set item active
if (Value != null)
{
var item = Items.FirstOrDefault(i => IsEquals(i.Value));
if (item != null)
{
item.Active = true;
}
}
}

private bool IsEquals(TValue? val) => Value != null && Value.Find(v => Equals(v, val)) != null;

private async Task<bool> OnBeforeStateChanged(CheckboxState state)
{
var ret = true;
if (state == CheckboxState.Checked)
{
var items = Items.Where(i => i.Active).ToList();
ret = items.Count < MaxSelectedCount;
}

if (!ret && OnMaxSelectedCountExceed != null)
{
await OnMaxSelectedCountExceed();
}
return ret;
}

/// <summary>
/// Checkbox 组件选项状态改变时触发此方法
/// </summary>
/// <param name="item"></param>
/// <param name="v"></param>
private async Task OnStateChanged(SelectedItem<TValue> item, bool v)
{
item.Active = v;
var vals = new List<TValue?>();
if (Value != null)
{
vals.AddRange(Value);
}

var val = vals.Find(i => IsEquals(item.Value));
if (v && val == null)
{
vals.Add(item.Value);
}
else
{
vals.Remove(val);
}

CurrentValue = vals;

Check warning on line 223 in src/BootstrapBlazor/Components/Checkbox/CheckboxListGeneric.razor.cs

View workflow job for this annotation

GitHub Actions / run test

Nullability of reference types in value of type 'List<TValue?>' doesn't match target type 'List<TValue>'.

if (OnSelectedChanged != null)
{
await OnSelectedChanged(Items, CurrentValue);
}
else
{
StateHasChanged();
}
}

/// <summary>
/// 点击选择框方法
/// </summary>
private Task OnClick(SelectedItem<TValue> item) => OnStateChanged(item, !item.Active);

/// <summary>
/// <inheritdoc/>
/// </summary>
public bool Equals(TValue? x, TValue? y) => this.Equals<TValue>(x, y);
}
Loading
Loading