Blazor数据绑定

数据绑定

Blazor支持在html元素中使用Razor语法进行绑定c#字段 属性或值

绑定语法

在html标签中,添加@bind="xxxx"即可实现绑定

@page "/bind"
<p>
    <input @bind="inputValue"/>
</p>
<p>
    <input @bind="InputValue" @bind:event="oninput" />
</p>
<ul>
    <li><code>用户输入的</code>:@inputValue</li>
    <li><code>用户输入的</code>@InputValue</li>
</ul>
@code {
    private string? inputValue;
    public string? InputValue { get; set; }
}

上面的代码 实现了当输入完成后鼠标离开input输入框会触发绑定事件

@bind:event 和@bind的区别

  • @bind 绑定更新不是实时的只有鼠标离开输入框后才会触发
  • @bind:event 会实时更新数据

格式化数据

blazor目前只支持DateTime格式字符串 通过@bind:format="yyyy-MM-dd"

@page "/data-binding"
<code>年月日</code> 
<input type="date" @bind="startDate" @bind:format="yyyy-MM-dd" />

<code>你选择的年月日 @startDate</code>
@code {
    private DateTime  startDate = new(2020, 1, 1);
}

绑定子组件属性

一个父界面往往由多个子组件组成 需要父组件参数绑定到子组件当中

  • 子组件定义
<input @bind="Title"/>

@code {
  [Parameter]
  public string Title { get; set; }
    [Parameter]
  public EventCallback<string> TitleChanged { get; set; }
}
  • 父组件调用
@page "/bind-theory"
<Test @bind-Title="InputValue"/>
@code {
    public string InputValue { get; set; }
}

posted @ 2022-06-21 22:44  赵福浩  阅读(513)  评论(0编辑  收藏  举报