File tree Expand file tree Collapse file tree 2 files changed +47
-1
lines changed
src/BootstrapBlazor/Components/Select Expand file tree Collapse file tree 2 files changed +47
-1
lines changed Original file line number Diff line number Diff line change @@ -26,6 +26,12 @@ public partial class Select<TValue> : ISelect, ILookup
2626 [ NotNull ]
2727 private ILookupService ? InjectLookupService { get ; set ; }
2828
29+ /// <summary>
30+ /// Gets or sets a value indicating whether the "active" state should be used when the associated value is null.
31+ /// </summary>
32+ [ Parameter ]
33+ public bool IsUseActiveWhenValueIsNull { get ; set ; }
34+
2935 /// <summary>
3036 /// Gets or sets the display template. Default is null.
3137 /// </summary>
@@ -444,10 +450,18 @@ private async Task OnChange(ChangeEventArgs args)
444450 {
445451 _lastSelectedValueString = "" ;
446452 _init = false ;
447- return null ;
453+
454+ return IsUseActiveWhenValueIsNull && ! IsVirtualize
455+ ? SetSelectedItemState ( GetItemByRows ( ) )
456+ : null ;
448457 }
449458
450459 var item = IsVirtualize ? GetItemByVirtualized ( ) : GetItemByRows ( ) ;
460+ return SetSelectedItemState ( item ) ;
461+ }
462+
463+ private SelectedItem ? SetSelectedItemState ( SelectedItem ? item )
464+ {
451465 if ( item != null )
452466 {
453467 if ( _init && DisableItemChangedWhenFirstRender )
Original file line number Diff line number Diff line change @@ -12,6 +12,38 @@ namespace UnitTest.Components;
1212
1313public class SelectTest : BootstrapBlazorTestBase
1414{
15+ [ Fact ]
16+ public async Task IsUseActiveWhenValueNull_Ok ( )
17+ {
18+ var tcs = new TaskCompletionSource ( ) ;
19+ var selectedValue = "" ;
20+ var cut = Context . RenderComponent < BootstrapBlazorRoot > ( pb =>
21+ {
22+ pb . AddChildContent < Select < string > > ( pb =>
23+ {
24+ pb . Add ( a => a . ShowSearch , true ) ;
25+ pb . Add ( a => a . Items , new List < SelectedItem > ( )
26+ {
27+ new ( "1" , "Test1" ) ,
28+ new ( "2" , "Test2" ) { Active = true }
29+ } ) ;
30+ pb . Add ( a => a . IsUseActiveWhenValueIsNull , true ) ;
31+ pb . Add ( a => a . OnSelectedItemChanged , item =>
32+ {
33+ selectedValue = item . Value ;
34+ tcs . SetResult ( ) ;
35+ return Task . CompletedTask ;
36+ } ) ;
37+ } ) ;
38+ } ) ;
39+
40+ await tcs . Task ;
41+
42+ // 组件未设置 Value 参数,应该使用 Test2 作为初始选项,并且触发 SelectedItemChanged 回调
43+ Assert . Equal ( "2" , selectedValue ) ;
44+ cut . Contains ( "value=\" Test2\" " ) ;
45+ }
46+
1547 [ Fact ]
1648 public async Task OnSearchTextChanged_Null ( )
1749 {
You can’t perform that action at this time.
0 commit comments