开发者

What's the difference between the two RegisterViewWithRegion overloads in Prism

I'm using Prism4 and in one of my modules I'm trying to register a view with a region and also handle its button clicked event (which is published when user clicks on a button on the view).

public class MyModule : IModule
{
    private readonly IUnityContainer container;
    private readonly IRegionManager regionManager;
    private readonly IEventAggregator eventAggregator;

    public MyModule(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator)
    {
        this.container     = container;
        this.regionManager = regionManager;
        this.eventAggregator = eventAggregator;

        eventAggregator.GetEvent<ViewAButtonClicked>().Subscribe(ViewAButtonClicked);
    }

    public void Initialize()
    {
        this.regionManager.RegisterViewWithRegion("MainRegion", typeof(ViewA));
        
        // this 2nd overload would work fine
        //this.regionManager.RegisterViewWithRegion("MainRegion", () => this.container.Resolve<ViewA>());            
    }

    public void ViewAButtonClicked()
    {
       // some handling code 
       // does *NOT* execute if using the 1st RegisterViewWithRegion overload
       // executes if using the 2nd Reg开发者_Python百科isterViewWithRegion overload
    }
}

The above code works fine up except that it does not execute the ViewAButtonClicked method.

If I switched to use the other overload (commented out in code above) then everything works as expected, the ButtonClicked method runs.

The descriptions from msdn are very similar and I'm not sure why it's giving me the different behavior described above. Why does one work and one doesn't when it comes to handling the button click event?

RegisterViewWithRegion(IRegionManager, String, Func<(Of <(Object>)>)): Associate a view with a region, using a delegate to resolve a concreate instance of the ? view. When the region get's displayed, this delelgate will be called and the result will be added to the views collection of the region.

RegisterViewWithRegion(IRegionManager, String, Type): Associate a view with a region, by registering a type. When the region get's displayed this type will be resolved using the ServiceLocator into a concrete instance. The instance will be added to the Views collection of the region.


The problem you are probably having is that with the typeof approach, the Module class is being GCed, and thus no subscriber is available.

With the other approach, as you are generating a lambda to register the view in the region, the Module class should be hanging around.

The event aggregator has an option to keep a reference alive (without using a weak reference), which should do the trick.


Perhaps ViewA has dependencies that aren't being resolved when you're not grabbing it from the container?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜