简体   繁体   中英

Binding in Blazor with Base & Derived classes

I have been trying to think of the best way to do this and I can't come up with what I believe to be an appropriate solution. Essentially I have the following:

Base Class Animal
Derived Class Dog : Animal
Derived Class Bird : Animal

Now on my page, I have bindings that always will occur in the Base class BUT there are scenarios where there are bindings on the page for the derived objects. This Base class is also the parameter for the page to load as of right now so I'm not too sure of the best approach here. It would look like something below.

[Parameter] Animal Animal {get; set;}

Then on the page I do the binding like such:

<input text=@bind-Value=@Animal.Name/>

My question is how would I add it such that I can map the derived objects properties if the base class grabbed is that of the type of the derived?

Something along the lines of if the animal was a bird, I can also bind the properties like such:

public class Animal
{
     public string Name {get; set;} 
}

public class Bird : Animal
{
     public string Wing {get; set;} 
}
<input text=@bind-Value=@Animal.Name/>
<input text=@bind-Value=@Animal.Wing/>

Is something like this possible or am I not appropriately structuring my classes? Any insight would be greatly appreciated.

I've been faced to the same issue and I resolved it by creating a component per derived type and a switch statement:

public abstract class Animal
{
     public abstract string KindName { get; }
     public string Name { get; set; } 
}

public class Bird : Animal
{
     public override string KindName => "Bird";
     public string Wing {get; set;} 
}

AnimalComponent.cs

public abstract class AnimalComponent<T> where T: Animal
{
     [CascadingParameter]
     public T Animal{ get; set; }
}

Bird.razor

@inherits AnimalComponent<Bird>

<input text=@bind-Value=@Animal.Wing/>

AnimalPage.razor

<CascadingValue Value="Animal">
    <input text=@bind-Value=@Animal.Name/>
    @switch (Animal.KindName)
    {
       case "Bird":
          <Bird />
          break;
       ...
    }
</CascadingValue>
@code {
    [Parameter] Animal Animal {get; set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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