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

本文关键字:对象 属性 转换 | 更新日期: 2023-09-27 18:36:36

>假设我有一个看起来像这样的对象图(这不是我真正的对象):

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

我想在"树视图"中呈现这些数据。我正在使用HierarchicalDataTemplate来管理每个子对象的显示方式,这很好用。

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

我想为不同的对象显示特殊图标。这就是它变得厚的地方:我可以显示某些类或类型的静态图像,我甚至可以显示基于实例化类的元数据的图标。我正在使用" IValueConverter "来执行此操作,效果很好。

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
}

我的"IValueConverter"有依赖项,我不知道如何注入这些依赖项,我已经搜索了所有内容以了解如何解决此问题。我见过的最接近解决这个问题的方法是在类中使用类似"ServiceLocator"内联的东西,但这对我来说似乎是一种反模式,它首先完全违背了 IoC 的目的。

有没有另一种方法可以让我的子图对象在没有转换器的情况下显示或"convert"他们的数据到"ImageSource"之类的东西中?

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

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

有点可耻,但我正在做类似于"服务定位器"的事情来向前滚动:

在 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
}