简体   繁体   English

如何查看Blazor是否设置了属性?

[英]How to check if a property has been set in Blazor?

My biggest issue here is when I have a property that can be nullable, but I want to check if it have been set, even if the value is null我最大的问题是当我有一个可以为 null 的属性时,但我想检查它是否已设置,即使值为null

Inside MyComponent I what I want to differ is this two casesMyComponent内部,我想要区分的是这两种情况

Passing Foo property传递Foo属性

<MyComponent Foo="@foo" />

@code {
    public Foo foo { get; set; }
}

Not passing Foo property不传递Foo属性

<MyComponent  />

But inside MyComponent , in both cases, Foo will be null .但是在MyComponent内部,在这两种情况下, Foo都是null

How can I know that Foo property is being passed, even if the value is the default value?我怎么知道正在传递Foo属性,即使该值是default值?

You can override the SetParametersAsync method to inspect the parameters that are set or not.您可以重写 SetParametersAsync 方法来检查已设置或未设置的参数。 Even if the value is null. If the parameter is not specified it will not be present in the collection.即使值为 null。如果未指定该参数,则它不会出现在集合中。

Eg例如

@code {

    [Parameter]
    public Foo Foo { get; set; }

    public override async Task SetParametersAsync(ParameterView parameters)
    {
        foreach(var prm in parameters)
        {
            System.Diagnostics.Debug.WriteLine($"Name: {prm.Name}");
            System.Diagnostics.Debug.WriteLine($"Value: {prm.Value?.ToString()}");
        }

        await base.SetParametersAsync(parameters);

    }
}

Documentation: https://learn.microsoft.com/en-us/do.net/api/microsoft.as.netcore.components.componentbase.setparametersasync?view=as.netcore-3.1文档: https://learn.microsoft.com/en-us/do.net/api/microsoft.as.netcore.components.componentbase.setparametersasync?view=as.netcore-3.1

<h3>Component</h3>

@code {
    private bool _setFromOutside;
    private Foo _foo = new Foo(); //values set from inside of your component

    [Parameter]
    public Foo Foo
    {
        get => _foo;
        set
        {
            _setFromOutside = true;
            _foo = value;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM