14

我在我的 WPF 应用程序中使用 PRISM 5。我的应用程序中的 Shell 视图有两个区域,将其视为 A 和 B。区域 A 包含一个弹出窗口(PRISM 5 交互功能用于显示弹出窗口)。

当我在视图的构造函数中创建弹出视图模型的实例时,该应用程序正在工作。

工作代码

public PopupView()
{
    InitializeComponent();
    this.DataContext = new PopupViewModel(); // Working code
}

但是当我尝试使用依赖注入创建视图模型实例时。应用程序 InitializeComponent();在父视图(视图 A)上失败。

DI 不工作代码

public PopupView(PopupViewModel viewModel)
{
    InitializeComponent(); // Failing in AView initialze
                           // before reaching here

    this.DataContext = viewModel;
}

在模块/引导程序中查看模型注册

container.RegisterType<AViewModel>();

发生了错误

发生 NULLReference 异常

Stacktrace(针对问题编辑)

at System.DefaultBinder.BindToMethod(BindingFlags bindingAttr, MethodBase[] match, Object[]& args, ParameterModifier[] modifiers, CultureInfo cultureInfo, String[] names, Object& state)
   at MS.Internal.Xaml.Runtime.DynamicMethodRuntime.CreateInstanceWithCtor(Type type, Object[] args)
   at MS.Internal.Xaml.Runtime.ClrObjectRuntime.CreateInstance(XamlType xamlType, Object[] args)
   at MS.Internal.Xaml.Runtime.PartialTrustTolerantRuntime.CreateInstance(XamlType xamlType, Object[] args)
   at System.Xaml.XamlObjectWriter.Logic_CreateAndAssignToParentStart(ObjectWriterContext ctx)
   at System.Xaml.XamlObjectWriter.WriteEndObject()
   at System.Windows.Markup.WpfXamlLoader.TransformNodes(XamlReader xamlReader, XamlObjectWriter xamlWriter, Boolean onlyLoadOneNode, Boolean skipJournaledProperties, Boolean shouldPassLineNumberInfo, IXamlLineInfo xamlLineInfo, IXamlLineInfoConsumer xamlLineInfoConsumer, XamlContextStack`1 stack, IStyleConnector styleConnector)
   at System.Windows.Markup.WpfXamlLoader.Load(XamlReader xamlReader, IXamlObjectWriterFactory writerFactory, Boolean skipJournaledProperties, Object rootObject, XamlObjectWriterSettings settings, Uri baseUri)
   at System.Windows.Markup.WpfXamlLoader.LoadBaml(XamlReader xamlReader, Boolean skipJournaledProperties, Object rootObject, XamlAccessLevel accessLevel, Uri baseUri)
   at System.Windows.Markup.XamlReader.LoadBaml(Stream stream, ParserContext parserContext, Object parent, Boolean closeStream)
   at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
   at MyNamespace.AView.InitializeComponent() in e:\xxx\xxxxx\xxx\AView.xaml:line 1
   at MyNamespace.AView..ctor(AViewModel viewModel) in e:\xxx\xxxxx\xxx\AView.xaml.cs:line 18

AViewModel(编辑了一个以避免项目特定信息)

 public class ItemSelectionNotification : Confirmation
 { 
      //This class includes properties related to my project
 }

public class AViewModel
 {
        public InteractionRequest<ItemSelectionNotification> ItemSelectionRequest { get; private set; }

        public AViewModel(EventAggregator eventAggregator,IUnityContainer container)
        {
            this.eventAggregator = eventAggregator;
            this.container = container;
            ItemSelectionRequest = new InteractionRequest<ItemSelectionNotification>();
            SettingsCommand = new DelegateCommand(OnClickSetting);    //Command for settings button click      
        }

        //Button click handling
        public void OnClickSetting()
        {                      
                var notification = new ItemSelectionNotification()
                    {
                        Title = "Items"
                    };
                this.ItemSelectionRequest.Raise(notification,OnSaveCallback);
         }  

        private void OnSaveCallback(PropertySelectionNotification returned)
        {
        }   
 }
4

2 回答 2

1

我将假设您在 XAML 中使用InteractionRequestTriggerwith来绑定到相应的 .PopupWindowActionPopupViewInteractionRequest

您不能传递PopupViewModel给 的构造函数,PopupView因为视图是由PopupWindowAction直接创建的,而不是由 DI 容器创建的。创建时,它会将视图设置为PopupWindowAction您传递给. 它有一个属性,可用于将您想要的任何数据传递给. 例如,你可以通过这里。PopupViewDataContextINotificationInteractionRequest.Raise(…)INotificationContentPopupViewPopupViewModel

编辑:我查了PopupWindowAction 资料,看来我错了。他们ServiceLocator在尝试实例化时使用PopupWindowAction.WindowContentType,因此从技术上讲,传递PopupViewModelPopupView' 的构造函数不应导致异常,但它仍然无用,因为视图DataContextINotification传递给InteractionRequest.

例子:

// PopupViewModel.cs
internal sealed class PopupViewModel
{
    public PopupViewModel(string message)
    {
        Message = message;
    }

    public string Message { get; }
}    

// PopupView.xaml
<UserControl …&gt;
    <Grid DataContext="{Binding Content, Mode=OneTime}">
        <Label Text="{Binding Message, Mode=OneTime}" />
    </Grid>
</UserControl>

// SomeViewModel.cs
internal sealed class SomeViewModel
{
    // Don't use DI-container references to construct objects, inject factories instead.
    // Also to keep things simple you can just create your PopupViewModel directly if it has no external dependencies.
    private readonly Func<string, PopupViewModel> _popupViewModelFactory;

    public SomeViewModel(Func<string, PopupViewModel> popupViewModelFactory)
    {
        _popupViewModelFactory = popupViewModelFactory;
    }

    public ICommand ShowPopupCommand { get; } = new DelegateCommand(DoShowPopup);

    public InteractionRequest<INotification> PopupRequest { get; } = new InteractionRequest<INotification>();

    private void DoShowPopup()
    {
        PopupRequest.Raise(new Notification
        {
            Content = _popupViewModelFactory("This is a Popup Message!")
        }, _ =>
        {
            // Callback code.
        });
    }
}

// SomeView.xaml
<UserControl …&gt;
    <i:Interaction.Triggers>
        <prism:InteractionRequestTrigger SourceObject="{Binding PopupRequest, Mode=OneTime}">
            <prism:PopupWindowAction WindowContentType="views:PopupView" />
        </prism:InteractionRequestTrigger>
    </i:Interaction.Triggers>

    <Button Command="{Binding ShowPopupCommand, Mode=OneTime}" />
<UserControl>

// SomeModule.cs (or maybe Bootstrapper.cs if you setup your container in Bootstrapper)
public sealed class SomeModule : IModule
{
    private readonly IUnityContainer _container;

    public SomeModule(IUnityContainer container)
    {
        _container = container;
    }

    public override void Initialize()
    {
        _container.RegisterType<Func<string, PopupViewModel>>(
            new InjectionFactory(c =>
                new Func<string, PopupViewModel>(message =>
                    c.Resolve<PopupViewModel>(
                        new ParameterOverride("message", message))));
    }
}
于 2017-03-29T23:44:28.947 回答
0

我认为您正在注册AViewModel,但 IoC 容器没有正确的实例或工厂PopupViewModel。从我的角度来看,您的 View 需要PopupViewModel作为依赖项,但容器无法解决它,因为此类型未注册。

此外,请将您的 XAML 文件推送到此处,因为 InitializeComponent() 方法引发了异常,这是因为标记不一致而发生的。因此,我们需要查看标记以便为您提供更多反馈。

于 2015-08-28T05:04:18.793 回答