如何在XAML中使用DI

时间:2018-08-14 06:48:34

标签: xamarin.forms prism

我希望我没有想像,但我想我在Prism和XF中看到了一种在XAML中使用依赖注入的行为的方法:

 <ContentPage.Behaviors>
   <helpers:MyPageBehavior>
      <x:Arguments>
             Have a type here maybe?
      </x:Arguments>             
   </helpers:MyPageBehavior>        
  </ContentPage.Behaviors>

MyPageBehavior:

class MyPageBehavior : Behavior<ContentPage>
{
      public MyPageBehavior(ISomeService someService)
      {
      }
}

2 个答案:

答案 0 :(得分:2)

假设我们有实现SomeService的类ISomeService,如下所示:

namespace YOURAPPNAME.Services
{
     public class SomeService : ISomeService
     {
          public SomeService()
          {
              Debug.WriteLine("Some Service Constructor Called");
          }
     }
}

然后在您的Xaml页面

<ContentPage ......
         xmlns:services="clr-namespace:YOURAPPNAME.Services;assembly=YOURAPPNAME"
         .....>

<ContentPage.Behaviors>
   <helpers:MyPageBehavior>
      <x:Arguments>
         <services:SomeService />
      </x:Arguments>             
   </helpers:MyPageBehavior>        
</ContentPage.Behaviors>

答案 1 :(得分:1)

您将要使用ContainerProvider。您可以从Prism Unit Tests的以下示例中看到如何使用它。您会注意到,模拟转换器要求通过DI注入IEventAggregator。在XAML中,您可以通过使用ContainerProvider并传入转换器的类型参数,将转换器添加到ResourceDictionary中。

MockConverter

using System;
using System.Globalization;
using Xamarin.Forms;
using Prism.Forms.Tests.Mocks.Events;
using Prism.Events;

namespace Prism.Forms.Tests.Mocks.Converters
{
    public class MockValueConverter : IValueConverter
    {
        private IEventAggregator _eventAggreator { get; }

        public MockValueConverter(IEventAggregator eventAggreator)
        {
            _eventAggreator = eventAggreator;
        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            _eventAggreator.GetEvent<TestActionEvent>().Publish("Convert");
            return value;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            _eventAggreator.GetEvent<TestActionEvent>().Publish("ConvertBack");
            return value;
        }
    }
}

模拟视图

<?xml version="1.0" encoding="UTF-8" ?>
<ContentPage
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:prism="clr-namespace:Prism.Ioc;assembly=Prism.Forms"
    xmlns:converters="using:Prism.Forms.Tests.Mocks.Converters"
    Title="{Binding Title}"
    x:Class="Prism.DI.Forms.Tests.Mocks.Views.XamlViewMock">
    <ContentPage.Resources>
        <ResourceDictionary>
            <prism:ContainerProvider x:TypeArguments="converters:MockValueConverter" x:Key="mockValueConverter" />
        </ResourceDictionary>
    </ContentPage.Resources>
    <Entry x:Name="testEntry"
        Text="{Binding Test,Converter={StaticResource mockValueConverter}}" />
</ContentPage>