将对象属性转换为不同的可查看对象

时间:2015-01-07 06:35:04

标签: c# wpf mvvm inversion-of-control ivalueconverter

说我有一个看起来像这样的对象图(这不是我的真实对象):

CaseFile
- Sections (collection)
  - Documents (collection of type:Document)
- Other Node
  - Other Children (collection)
    - More children (collection)

我想在TreeView'中提供这些数据。我使用HierarchicalDataTemplate来管理每个子对象的显示方式,这非常有用。

<HierarchicalDataTemplate DataType="x:Type local:Document">
  <StackPanel Orientation="Horizontal">
  <Image Source="{Binding FileName, Converter="MyResourceConverter"}" />
  <TextBlock Foreground="Red" Text="{Binding Name}" />
  </StackPanel>
</HierarchicalDataTemplate>

我想显示不同对象的特殊图标。在这里它变厚:我可以显示某些类或类型的静态图像,我甚至可以根据实例化类的元数据显示图标。我正在使用&#39; IValueConverter&#39;这样做,效果很好。

class MyResourseConverter : IValueConverter
{
  private static readonly IImageManager _imageManager = 
    new CachedImageManager(new SystemImageManager());


  public MyResourceConverter() // place where I'd like to inject this IImageManager
  {
  }
  //... IValueConverter Properties
  //... That uses the _imageManger
}

我的&#39; IValueConverter&#39;有依赖关系,我无法弄清楚如何注入这些依赖关系,我已经搜遍了所有人,看看如何解决这个问题。我认为最接近解决这个问题的方法是使用&#39; ServiceLocator&#39;在课堂上内联,但这对我来说似乎是一种反模式,它首先完全打败了IoC的目的。

是否有另一种方法可以让我的子图形对象显示或“convert&#39;他们的数据包括&#39; ImageSource&#39;没有转换器?

2 个答案:

答案 0 :(得分:0)

您可以在XAML中使用x:Arguments通过转换器构造函数注入依赖项。

答案 1 :(得分:0)

有点可耻但是我做了类似于ServiceLocator&#39;的事情。向前滚动:

在App.xaml.cx中

using System.Windows;
using SimpleInjector;

public partial class App : Application
{
    private static Container container;

    [System.Diagnostics.DebuggerStepThrough]
    public static TService GetInstance<TService>() where TService : class {
        return container.GetInstance<TService>();
    }

    protected override void OnStartup(StartupEventArgs e) {
        base.OnStartup(e);
        Bootstrap();
    }

    private static void Bootstrap()  {
        // Create the container as usual.
        var container = new Container();

        // Register your types, for instance:
        container.RegisterSingle<IImageManager>(() => new CachedImageManager(new SystemImageManager()););

        // Optionally verify the container.
        container.Verify();

        // Store the container for use by the application.
        App.container = container;
    }
}

转换器

class MyResourseConverter : IValueConverter
{
  private static readonly IImageManager _imageManager = 
    new CachedImageManager(new SystemImageManager());

  public MyResourceConverter()
  {
     _imageManager = App.GetInstance<IImageManager>();
  }

  //... IValueConverter Properties
  //... That uses the _imageManger
}