Tutorial
Start and setup
After the component is placed on a page it is necessary to set up couple of parameters to make component work properly (and to remove the compiler warnings).
The component requires type parameter T
, but this type can be omitted and then inferred from property such as Items
.
<DropDownList Items="_products" /> @code { public record Product (string Title, double Price); private List<Product> _products = [ new Product("Sofa", 200.0), new Product("TV", 800)]; }
Templating
If your class overrides standard ToString
method, the component will work as-is, but for better control it is better to set up ItemTemplate
parameter.
<DropDownList Items="_products">
<ItemTemplate>
@context.Value.Title
</ItemTemplate>
</DropDownList>
Inside the template developer can access context (instance of StateContext
) that holds Item currently being rendered (Value
), but also other properties such as IsSelected
and IsFocused
. That means that with little bit of logic inside the template, different results can be achieved depending on component and item state.
Example
<DropDownList Items="_products"> <ItemTemplate> @if (context.IsSelected) { <span>Selected: </span> } @context.Value.Title </ItemTemplate> </DropDownList>
There is also SelectedItemTemplate
parameter that be set up to represent currently selected item (when the list is closed):
Example
<DropDownList Items="_products" style="width: 120px"> <ItemTemplate> @context.Value.Title </ItemTemplate> <SelectedItemTemplate> <div style="display: flex; justify-content: space-between"> <div>@context.Title</div> <div style="color: red">$@context.Price</div> </div> </SelectedItemTemplate> </DropDownList>
Binding
At the end selected item need to be bind to some variable of the same type. In example our variable _selectedProduct
is nullable so the other parameters need to be adjusted slightly for null check safety.
<DropDownList Items="products" @bind-SelectedItem="selectedProduct" style="width: 120px"> <ItemTemplate> @context.Value?.Title </ItemTemplate> <SelectedItemTemplate> <div style="display: flex; justify-content: space-between"> <div>@context?.Title</div> <div style="color: red">$@context?.Price</div> </div> </SelectedItemTemplate> </DropDownList> @code { private Product? _selectedProduct; }