Home > Net >  Constructor with parameters for XAML elements in Xamarin Forms
Constructor with parameters for XAML elements in Xamarin Forms

Time:09-24

Is it possible to create XAML element with parametrized constructor using dependency injection service? Or is there some other way to pass dependencies? I would like to have Behavior with some dependency services. I thought the DependencyResolver.ResolveUsing is going to solve my problem, but this method only allows to resolve special types of objects like renderers or effects. I can bind to viewmodel properties but this will produce large xaml instead of just simple <SomeBehavior/>

CodePudding user response:

In Prism (where application inherits from PrismApplication), It's pretty simple

Let's say you have these somewhere

public interface IService
{
    void Log(string msg);
}

public class ConcreteService : IService
{
    public void Log(string msg)
    {
        Console.WriteLine(msg);
    }
}

Step1. link the service with the implementation

protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
    containerRegistry.RegisterSingleton<IService, ConcreteService>();
    // ..
}

Step2. get it in the ctor of the view

public partial class MainPage
{
    public MainPage(IService service)
    {
        InitializeComponent();
        service.Log("After InitializeComponent..");
    }
}

CodePudding user response:

I am afraid that setting dependency for XAML element is not supported.

You can check the Microsoft document about XAML. Please feel free to contact us If you have other question

CodePudding user response:

No answer satisfied my needs so I share my solution. I use StaticResources (Application.Current.Resources) as ServiceLocator. This way I can access required services from my behavior without boilerplate code. Yes, I know it is not a perfect solution, but seems the best in my sytuation.

  • Related