Search code examples
c#xamlxamarinmvvmprism

Prism Inject XAML UnitValueConverter with additional attributes


I'm currently implementing a Xamarin MVVM app using Prism. I have the following IValueConverter:

public class MyConverter: IValueConverter, INotifyPropertyChanged
{
  private readonly IMyInjectedService _myInjectedService;

  public UnitVisualizationConverter(IMyInjectedService myInjectedService)
  {
     _myInjectedService = myInjectedService;
  }

  private string _myProperty= null;

  public event PropertyChangedEventHandler PropertyChanged;

  public string MyProperty
  {
    get => _myProperty;
    set 
    { 
      _unit = _myProperty; 
      OnPropertyChanged(); 
    }
  }

  protected virtual void OnPropertyChanged(string propertyName = null)
  {
    if (PropertyChanged != null)
      PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }


  public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
  {
    //some code
  }

  public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  {
    // some code
  }
}

I was using the following XAML-Code to get the converter into my view and inject MyInjectedService:

<ResourceDictionary>
  <ioc:ContainerProvider x:TypeArguments="valueConverters:MyConverter"
    x:Key="MyConverter"
    MyProperty ="{Binding DataContext.MyProperty}"/>
</ResourceDictionary>

So I like to bind the value of MyProperty to a coresponding value in my ViewModel. When implementing this I got the error message: The property 'MyProperty' was not found in type 'ContainerProvider`1'. Is there a solution for this problem? Thank you for your help.


Solution

  • I found a solution by myself. I changed the constructors of the value converter to:

     public UnitVisualizationConverter(IMyInjectedService myInjectedService)
    {
      _myInjectedService = myInjectedService;
    }
    public UnitVisualizationConverter(): this(App.ContainerProvider.Resolve<IMyInjectedService>())
    {
    }
    

    So I can use the "normal" XAML declaration of the converter.

    <myPrefix:MyConverter x:Key="myConverter" MyProperty="{Binding... }"/>
    

    A requirement for this solution is that the Prism ContainerProvider is declared public and static.