柱形图注入具有附加属性的XAML UnitValueConverter

pkmbmrz7  于 2023-03-27  发布在  其他
关注(0)|答案(1)|浏览(90)

我目前正在使用Prism实现一个Xamarin MVVM应用。我有以下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
  }
}

我使用以下XAML代码将转换器放入视图并注入MyInjectedService

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

所以我想把MyProperty的值绑定到我的ViewModel中的一个对应的值。当实现这个时,我得到了错误消息:The property 'MyProperty' was not found in type 'ContainerProvider1'` .这个问题有解决方案吗?谢谢你的帮助。

kgsdhlau

kgsdhlau1#

我自己找到了一个解决方案。我将值转换器的构造函数改为:

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

所以我可以使用转换器的“普通”XAML声明。

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

此解决方案的一个要求是Prism ContainerProvider被声明为public和static。

相关问题