gpt4 book ai didi

c# - 将 Unity 容器传递给 WPF 转换器类

转载 作者:太空宇宙 更新时间:2023-11-03 10:43:19 24 4
gpt4 key购买 nike

我是 WPF 新手。

我想知道如何将我的 IUnityContainer 类依赖注入(inject)到仅在 XAML 中具有代码的 ViewModel。

小更新:
有一个名为:LiveVideoTileControl 的类 - 我已将容器添加到它。

我有带有特定转换器的窗口:

<UserControl x:Class="Driver.Test.Views.LiveVideoTileControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:ViewModels="clr-namespace:Driver.Test.ViewModel"
xmlns:Driver="clr-namespace:Driver.Test.DriverRelated"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300" >
<UserControl.Resources>
<Driver:CameraToMediaElementConverter x:Key="converter"/>
</UserControl.Resources>
<ScrollViewer>
<Grid>
<ContentControl Content="{Binding CameraEntity,Converter={StaticResource converter}}" HorizontalContentAlignment="Center" VerticalContentAlignment="Center">
</ContentControl>
</Grid>
</ScrollViewer>
</UserControl>

如何将容器注入(inject)类“CameraToMediaElementConverter”?

class CameraToMediaElementConverter : IValueConverter
{
public object Convert(object cameraEntity, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((cameraEntity as ICameraEntity) != null)
{
return DriverWrapper.GetControlForCamera((ICameraEntity)cameraEntity);
}
throw new NotImplementedException();
}

public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

最佳答案

如果有人会以某种方式到达这里并且仍然会寻找答案,这就是我在我的应用程序中所做的并且它工作得很好。转换器类的局限性在于您无法传递对统一容器实例的引用以通过构造函数注入(inject)您的服务。

在 Bootstrapper 类或您在启动时注册服务的任何其他地方(这里是 Prism 的 Bootstrap ConfigureContainer 的一部分):

   protected override void ConfigureContainer()
{
base.ConfigureContainer();
Container.RegisterType<IShellViewModel, ShellViewModel>();
Container.RegisterType<MyService>(new ContainerControlledLifetimeManager());
Container.RegisterInstance<MyService>(new MyService());
Application.Current.Resources.Add("IoC", this.Container);
}

注意最后一行:

            Application.Current.Resources.Add("IoC", this.Container);

在转换器类构造函数中:

        UnityContainer unityContainer = (UnityContainer)Application.Current.Resources["IoC"];

现在您可以轻松地从 Unity 容器中解析对象的任何实例:

service = (MyService) unityContainer.Resolve<MyService>();

关于c# - 将 Unity 容器传递给 WPF 转换器类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24473767/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com