如何在blazor中进行双链绑定?

时间:2020-03-11 12:48:49

标签: c# blazor matblazor asp.net-blazor

我正在使用Mat Blazor TextField,并且想为其做包装,因此,如果有一天我想将其更改为另一个库,则更容易,并且不需要在代码中的任何地方进行更改。

因此,我制作了一个带有一些基本输入参数的BaseTextInput类,并创建了一个自己的TextField类,该类继承自BaseTextInput并在内部使用了MatBlazor

BaseTextInput.cs

public abstract class BaseTextInput : BaseDomComponent
{                
    [Parameter]
    public bool Enabled { get; set; } = true;

    [Parameter]
    public string PlaceHolder { get; set; }

    [Parameter]
    public string Label { get; set; }

    [Parameter]
    public string Value { get; set; }

    [Parameter]
    public EventCallback<string> OnChange { get; set; }

    [Parameter]
    public InputType InputType { get; set; } = InputType.Text;

}

TextInput.razor.cs

public partial class TextInput : BaseTextInput
{
    private bool Disabled => !Enabled;

    private string Type => InputType.ToLower();

}

TextInput.razor

@inherits BaseTextInput

<MatTextField @bind-Value="Value"
              Label="@Label"
              PlaceHolder="@PlaceHolder"
              Disabled="@Disabled"
              Type="@Type" />

但是问题是,当我使用自己的TextInput时,它不会更改值

//     the @bind-Value doesn't work
<TextInput @bind-Value="TextInputValue" Label="My Label" /> 

@code {
    public string TextInputValue { get; set; }
}

我还搜索了一些解决方案,并在出色的文档中找到了Child-to-parent binding with chained bind

所以我将其更改为

TextInput.razor

@inherits BaseTextInput

<MatTextField Value="@Value"
              Label="@Label"
              PlaceHolder="@PlaceHolder"
              Disabled="@Disabled"
              Type="@Type" 
              OnInput="@(e => Value = e.Value.ToString())"/>

但仍然没有用。

我在这里做错了什么?为什么不绑定?

如果我在没有包装器的情况下使用MatTextField,则一切正常,但是当我添加不应更改任何内容的包装器时,仅将参数传递下来是行不通的。

编辑:

这个问题不仅发生在MatBlazor上,我在Telerik和其他库中进行了测试,并且所有情况都在发生,所以我认为问题更多的是bind,而不是它自己的库

0 个答案:

没有答案